Beautiful Soup 常用方法

Beautiful Soup 是一个可以从HTML或XML文件中提取数据的Python库

初始化

from bs4 import BeautifulSoup
soup = BeautifulSoup(html_doc)

查找
find_all( name , attrs , recursive , text , **kwargs )
soup.find_all(‘title’, limit=1)等价于soup.find(‘title’)
name 参数可以查找所有名字为 name 的tag
通过 text 参数可以搜搜文档中的字符串内容
attrs 搜索tag的属性
limit 截取
Beautiful Soup会检索当前tag的所有子孙节点,如果只想搜索tag的直接子节点,可以使用参数 recursive=False .

soup.find_all('b')
soup.find_all(id='link2')
soup.find_all(re.compile("^b"))
soup.find_all(["a", "b"])
soup.find_all(True)

获取内容
如果只想得到tag中包含的文本内容,那么可以嗲用 get_text() 方法,这个方法获取到tag中包含的所有文版内容包括子孙tag中的内容,并将结果作为Unicode字符串返回:

soup = BeautifulSoup(markup)
soup.get_text()
link.get('href')

猜你喜欢

转载自blog.csdn.net/lkjasdgfh/article/details/80432264