天天看点

Python爬虫第二课BeautifulSoup

Python爬虫第二课

  • BeautifulSoup
    • 下载插件
    • 提取数据(find(),find_all(),Tag对象)

BeautifulSoup

下载插件

windowns: pip install BeautifulSoup4

Mac: pip3 install BeautifulSoup4

bs对象 = BeautifulSoup(想要解析的文本,‘解析器’)

在括号中,要输入两个参数,第0个参数是要被解析的文本,注意了,它必须必须必须是字符串。

括号中的第1个参数用来标识解析器,我们要用的是一个Python内置库:html.parser。(它不是唯一的解析器,但是比较简单的)

例子:

#(来自风变编程)
import requests
from bs4 import BeautifulSoup
#引入BS库
rs = requests.get('https://localprod.pandateacher.com/python-manuscript/crawler-html/spider-men5.0.html')
html = rs.text
soup = BeautifulSoup(html ,'html.parser')#把网页解析为BeautifulSoup对象
print(soup)
           

rs.text :<class ‘str’>

soup = BeautifulSoup(html ,‘html.parser’):<class ‘bs4.BeautifulSoup’>

rs.text是属于字符串而**soup = BeautifulSoup(html ,‘html.parser’)**属于被解析过的BeautifulSoup对象,之所以打印出来的效果是一样的,是因为BeautifulSoup对象在直接打印的时候会调用该对象内的str方法,所以直接打印 bs 对象显示字符串是str的返回结果。

提取数据(find(),find_all(),Tag对象)

find()与find_all()是BeautifulSoup对象的两个方法,它们可以匹配html的标签和属性,把BeautifulSoup对象里符合要求的数据都提取出来。

它俩的用法基本是一样的,区别在于,find()只提取首个满足要求的数据,而find_all()提取出的是所有满足要求的数据。

方法 作用 用法 示例
find() 提取满足要求的首个数据 BeautifulSoup对象.find(标签,属性) soup.find(‘div’,class_=‘books’)
find_all() 提取满足要求的所有数据 BeautifulSoup对象.find(标签,属性) soup.find_all(‘div’,class_=‘books’)

*class_,这里有一个下划线,是为了和python语法中的类 class区分,避免程序冲突。当然,除了用class属性去匹配,还可以使用其它属性,比如style属性等。

find() 例子:

#(来自风变编程)
import requests
from bs4 import BeautifulSoup
url = 'https://localprod.pandateacher.com/python-manuscript/crawler-html/spder-men0.0.html'
res = requests.get (url)
print(res.status_code)
soup = BeautifulSoup(res.text,'html.parser')
item = soup.find('div') #使用find()方法提取首个<div>元素,并放到变量item里。
print(type(item)) #打印item的数据类型
print(item)       #打印item 
           

打印结果为:

200
<class 'bs4.element.Tag'>
<div>大家好,我是一个块</div>
           

可以看出来特它的数据类型是一个Tag类型的

find_all() 例子:

#(来自风变编程)
import requests
from bs4 import BeautifulSoup
url = 'https://localprod.pandateacher.com/python-manuscript/crawler-html/spder-men0.0.html'
res = requests.get (url)
print(res.status_code)
soup = BeautifulSoup(res.text,'html.parser')
items = soup.find_all('div') #用find_all()把所有符合要求的数据提取出来,并放在变量items里
print(type(items)) #打印items的数据类型
print(items)       #打印items
           

打印结果为:

200
<class 'bs4.element.ResultSet'>
[<div>大家好,我是一个块</div>, <div>我也是一个块</div>, <div>我还是一个块</div>]
           

运行结果是那三个

元素,它们一起组成了一个列表结构。打印items的类型,显示的是<class ‘bs4.element.ResultSet’>,是一个ResultSet类的对象。其实是Tag对象以列表结构储存了起来,可以把它当做列表来处理。

遍历出来的元素的数据类型是<class ‘bs4.element.Tag’>

这与find()提取出来的数据类型是一样的

Tag类对象的常用属性和方法

方法 作用
Tag.find()和Tag.find_all() 提取Tag中的Tag
Tag.text 提取Tag中的文字
Tag[‘属性名’] 输入参数:属性名,可以提取Tag中这个属性的值
Python爬虫第二课BeautifulSoup

ps:革命尚未成功,同志仍需努力!!!

继续阅读