1、常用格式
1 2 3
| from bs4 import BeautifulSoup
soup = BeautifulSoup(content, 'html.parser')
|
参数说明:
content:使用requests或其他方式,发出请求后获取到的服务器响应内容,通常应该为HTML格式。
html.parserHTML4格式解析器
2、常用的属性
标签自身属性:
1 2 3 4 5 6 7 8 9
| tag:标签,例如soup.tag可以将指定的标签以及内部的内容返回 name:标签名,例如:soup.tag.name返回指定标签的名字 attrs:标签属性,在HTML中一个标签可以有0到N个标签,因此标签属性为字典类型,例如:soup.tag.attrs['class'] string:标签内的文本内容,例如:soup.tag.string 标签树的属性: contents例如:soup.tag.contents,将指定的标签名内所有的标签都以列表形式返回。 children:例如:soup.tag.children,将指定的标签中所有的子标签内容,都以迭代器形式返回,进行遍历查询。 descendants:例如:soup.tag.descendants,将指定的标签中所有的子标签、孙标签都以迭代器形式返回,进行遍历查询。 注意:BeautifulSoup对象,作为标签树的根节点,即HTML节点
|
3、常用方法
1)函数格式:soup.find(name,attrs)
参数说明:
name:标签名
attrs:标签中的属性值(属性=‘值’)
返回值:返回查找到第一个符合条件的标签以及内部元素
2)函数格式:soup.find_all(name,attrs)
函数参数与上面find()相同
返回值:返回符合条件的所有的标签,以列表形式返回。
4、bs4的遍历模式
在BeautifulSoup中,有三种遍历模式:
1)下行遍历
1 2
| children、descendants、contents find()、find_all()
|
2)上行遍历
1 2
| parent、parents find_parent()、find_parents()
|
3)平行遍历
1 2 3 4
| next_sibling、next_siblings previous_sibling、previous_siblings find_next_sibling()、find_next_siblings() find_previous_siblings()、find_previous_sibling()
|