pip install beautifulsoup4
from bs4 import BeautifulSoup
基本元素:
tag 标签
Name tag.name 标签名
Attributes tag.attrs 标签属性,字典类型
NavigableString 标签内非属性字符串 tag.string
Comment 标签内字符串的注释部分
r = requests.get('url')
t = r.text
soup = BeautifulSoup(t, 'html.parser')
soup.a返回第一个a标签内容
soup.a.name a标签的名字
soup.a.parent.name a父标签的名字
soup.a.string a标签的非属性字符串
soup.a.contents 标签树下行遍历,保存子标签所有内容的列表
soup.a.children 子标签,与contents类似,迭代类型 for child in children:
soup.a.descendants 子孙标签,同上
上行遍历
soup.a.parent 节点的父亲标签,全部内容,包含a标签自己
soup.a.parents 先辈标签的迭代类型,用于循环
平行遍历:需在同一父节点下
.next_sibling 返回顺序的下一个平行节点标签
.previous_sibling 返回顺序的上一个平行节点标签
.next_siblings 返回顺序的后续所有平行节点标签
.previous_siblings 返回顺序的前续所有平行节点标签
print(soup.prettify())
按html格式显示
标签也可用同函数
soup.find_all('a') 检索标签名称为a的内容
soup.find_all(['a','b'])
<tag>.find_all(name, attrs, recursuve, string, **Kwargs)
name: 标签名
attrs: 标签属性值中的字符串。例如:'python', name='python', age=re.compile('1')
recursive: 是否对子孙标签检索,默认True
string: 非属性字符串内容搜索
<tag>(...) 等价于 <tag>.find_all(...)
soup(...) 等价于 soup.find_all(...)
其余方法:
.find() 搜索只返回一个结果,同.find_all()
.find_parents() 搜索前辈节点,返回列表类型
.find_parent() 返回一个先辈结果
.find_next_siblings() 搜索后续平行节点,返回列表类型
.find_next_siblings() 返回一个后续结果
.find_previous_siblings() 搜索前序平行节点,返回列表类型
.find_previous_siblings() 返回一个前序结果
soup.find_all(['a','b'])
<tag>.find_all(name, attrs, recursuve, string, **Kwargs)
name: 标签名
attrs: 标签属性值中的字符串。例如:'python', name='python', age=re.compile('1')
recursive: 是否对子孙标签检索,默认True
string: 非属性字符串内容搜索
<tag>(...) 等价于 <tag>.find_all(...)
soup(...) 等价于 soup.find_all(...)
其余方法:
.find() 搜索只返回一个结果,同.find_all()
.find_parents() 搜索前辈节点,返回列表类型
.find_parent() 返回一个先辈结果
.find_next_siblings() 搜索后续平行节点,返回列表类型
.find_next_siblings() 返回一个后续结果
.find_previous_siblings() 搜索前序平行节点,返回列表类型
.find_previous_siblings() 返回一个前序结果