作者:PN喜欢建设城市ae | 来源:互联网 | 2023-10-10 10:12
python爬虫常用库之bs4
bs4全名BeautifulSoup,是编写python爬虫常用库之一,主要用来解析html标签。
1.安装
pip install beautifulsoup4
或
python -m pip install beautifulsoup4
2.基本使用方法
bs4中最基础的使用是BeautifulSoup类的使用,注意大小写哦。
用BeautifulSoup来解析html:
from bs4 import BeautifulSoup
soup1 = BeautifulSoup(" A Html Text", "html.parser")
soup2 = BeautifulSoup(open("d://demo.html"), "html.parser")
两个参数:第一个参数是要解析的html文本,第二个参数是使用那种解析器,对于HTML来讲就是html.parser,这个是bs4自带的解析器。 还可以安装lxml库来解析HTML或者XML,安装html5lib来解析html5lib。
#lxml解析html(需pip install lxml)
BeautifulSoup(html,'lxml')
#lxml解析XML
BeautifulSoup(xml,'xml')
#html5lib解析(需安装: pip install html5lib)
BeautifulSoup(html5,'html5lib')
2.1 BeautifulSoup基本元素
BeautifulSoup基本元素有:
基本元素 |
说明 |
---|
Tag |
标签,基本信息组织单元,用<>和>标明开头和结尾 |
Name |
标签的名字, ... 的名字就是’p',用法<>.name |
Attributes |
标签属性,字典形式,用法:<>.attrs['href'] |
NavigableString |
标签内非属性字符串, 这是非属性字符串 ,用法:<>.string |
Comment |
标签内的注释部分 显示的内容 |
2.1.1 Tag标签
任何存在于html语法中的标签都可以用soup.访问获得。
当HTML文档中存在多个相同的tag时,soup.返回第一个
>>> soup2 = BeautifulSoup("The Contents of b in first p
The second p
","html.parser")
>>> soup2.p
The Contents of b in first p
2.1.2 Tag的name
每个Tag都有自己的名字,通过.name获取,字符串类型
>>> soup2.p.name
'p'
2.1.3 Tag的attrs(属性)
一个Tag可以有0个或多个属性,字典类型。
>>> soup2.p.attrs
{'class': ['title']}
>>> soup2.p.attrs['class']
['title']
2.1.4 Tag的NavigableString
NavigableString可以跨越多个层次的标签。
>>> soup2.p
The Contents of b in first p
>>> soup2.p.string
'The Contents of b in first p'
>>>
2.1.5 Tag 的Comment
Comment是一种特殊类型
>>> soup3 = BeautifulSoup("This is a NavigableString
","html.parser")
>>> soup3.p
This is a NavigableString
>>> soup3.b
>>> soup3.p.string
'This is a NavigableString'
>>> type(soup3.p.string)
>>> soup3.b
>>> soup3.b.string
' This is a Comment '
>>> type(soup3.b.string)
>>>
....
p ->tag.name 'p'
class="title" ->
tag.attrs (字典列表)
... ->
NavigableString OR Comment
2.2 使用bs4遍历html内容
HTML是个树状结构,<>...>构成了从属关系。对HTML的遍历,有下行遍历,上行遍历和平行遍历三种遍历途径或方法。
2.2.1 下行遍历
属性 |
说明 |
---|
.contents |
子节点的列表,将所有的儿子节点存入列表 |
.children |
子节点的迭代类型,与.contents类似,主要用于循环遍历子节点 |
.descendants |
子孙节点的迭代类型,包含所有子孙节点,用于循环遍历。 |
BeautifulSoup类型是标签树的根节点。
soup.head
soup.head.contents
soup.body.contents
len(soup.body.contents)
soup.body.contents[0]
遍历子节点:
for child in soup.body.children:
print(child)
遍历所有子孙节点:
for child in soup.body.descendants:
print(child)
2.2.2 上行遍历
属性 |
说明 |
.parent |
节点的父节点 |
.parents |
节点的先辈节点标签的迭代类型,用于循环遍历先辈节点。 |
>>> soup
The demo python introduces several python courses.
Python is a wonderful general-purpose programming language. You can learn Python from novice to professional by tracking the following courses:
Basic Python and Advanced Python.
>>> soup.title.parent
>>> soup.html.parent
The demo python introduces several python courses.
Python is a wonderful general-purpose programming language. You can learn Python from novice to professional by tracking the following courses:
Basic Python and Advanced Python.
>>> soup.parent
>>>
注意:..标签的父节点是其自身
而soup本身的父节点是空。
进行先辈节点遍历时,包括soup自身,实际使用时需要判断。
for parent in soup.a.parents:
if parent is None:
print(parent)
else:
print(parent.name)
2.2.3 平行遍历
属性 |
说明 |
.next_sibling |
返回按照HTML文本顺序的下一个平行节点标签 |
.previous_sibling |
返回按照HTML文本顺序的上一个平行节点标签 |
.next_siblings |
迭代类型,返回按照HTML文本顺序的后续所有平行节点标签 |
.previous_siblings |
迭代类型,返回按照HTML文本顺序的前续所有平行节点标签 |
平行遍历发生在同一个父节点下的各节点之间。
soup.a.next_sibling
soup.a.next_sibling.nextsibling
soup.a.previous_sibling
soup.a.parent
遍历后续节点:
for sibling in soup.a.next_siblings:
print(sibling)
遍历前续节点:
for sibling in previous_siblings:
print(sibling)
3. 基于bs4库的HTML格式输出
3.1 prettify()方法
.prettify()为HTML文本<>及其内容增加‘n'
.prettify()可用于标签,方法.prettify()
print(soup.a.prettify())
3.2 bs4k库的编码
bs4库将任何HTML输入都变成utf-8编码,python3.x 默认支持编码是utf-8。完美匹配!
4.使用bs4进行HTML内容查找
使用bs4进行HTML内容解析查找,基本方法是使用<>.find_all()来进行
4.1 .find_all()的基本使用方法
基本格式:
.find_all(name, attrs, recursive, string, **kwargs)
其返回值为一个列表,存储查找的结果
参数:
name -> 对标签名称的检索字符串,可以是个字符串列表,表达“或”关系
soup.find_all('a')
soup.find_all(['a','b'])
soup.find_all(True)
attrs
->
对标签属性值的检索字符串,可标注属性检索
soup.find_all('a', 'title')
soup.find_all(id='link1')
soup.find_all(attrs = {"class":"course"})
recursive ->
是否对子孙全部检索,默认True
string ->
<>...>中的....的检索字符串
soup.find_all(string = 'This is a sample')
因为find_all太常用了,所以有简略用法:
(...) <-->
.find_all(...)
soup(...) <-->
soup.find_all(...)
程序员果然都是懒人..........
4.2 扩展方法
方法 |
说明 |
---|
<>.find() |
搜索且只返回一个结果,同.find_all()参数 |
<>.find_parents() |
在先辈节点中搜索,返回列表类型,同.find_all()参数 |
<>.find_parent() |
在先辈节点中返回一个结果,同.find()参数 |
<>.find_next_siblings() |
在后续平行节点中搜索,返回列表类型,同find_all()参数 |
<>.find_next_sibling() |
在后续平行节点中搜索,返回一个结果,同find()参数 |
<>.find_previous_siblings() |
在前续平行节点中搜索,返回列表类型,同find_all()参数 |
<>.find_previous_sibling() |
在前续平行节点中搜索,返回一个结果,同find()参数 |