使用
from bs4 import BeautifulSoup
# 创建BeautifulSoup对象
soup = BeautifulSoup(html,'lxml',from_encoding='utf-8')
对象种类
tag即标签,有属性name、attribute
soup.p查找是第一个符合要求标签,是第一个!!
获取标签名soup.title.name
获取p标签的属性class的值,输出为列表
soup.p['class']
soup.p.get('class)
获取标签内部文字,.string如果标记没内容,如果子节点唯一会输出子节点内容,不唯一,无法判断,输出None
soup.p.string
注意注释文字也会被提取出来,解决方法,判断一下
if type(soup.a.string) == bs4.element.Comment:
print(soup.a.string)
.strings输出标签包含的所有字符串,使用循环遍历,会输出空内容
.stripped_strings输出内容就没有空
遍历文档树
输出标签全部子节点,输出为列表
soup.head.contents
.children是返回一个生成器,对其子节点进行循环
for child in soup.head.children:
print(child)
.parent父节点soup.title.parent
.nesxt_sibling下个兄弟节点,不存在就返回None
.previous_sibling上个兄弟节点,不存在就返回None
.next_element后一个节点,针对所有,不分层次
.previous_element前一个节点
搜索文档树
find_all(name, attrs, recursive, text, **kwargs)
name查找的标签名,匹配参数字符串、正则、列表、Ture和方法,返回值为列表
查找属性id为link2的标签,属性可以多制定
soup.find_all(id=‘link2’)
soup.find_all(id=‘link2’, href=re.compile(“elsie”)
查找属性href值含有elise的标签
soup.find_all(href=re.compile(“elsie”)
如果查找标签a,使用class过滤,需要加下划线
soup.find_all(“a”,class_=“sister”)
text搜索文档中字符串,参数可为字符串、正则、列表、Ture
soup.find_all(“a”,text=“Elsie”)
limit参数,限制符合条件的返回数量
soup.find_all(“a”,limit=2)
find_all为搜索所有节点,加入参数recursive=False,就只搜索子节点
soup.find_all(“title”,recursive=False)