beautifulsoup是一个灵活又方便的网页解析库,处理高效,支持多种解析器。
from bs4 import BeautifulSoup
html = '''
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title"><b>The Dormouse's story</b></p>
<p class="story">Once upon a time there were three little sisters; and their names were
<a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>,
<a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
<a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;
and they lived at the bottom of a well.</p>
<p class="story">...</p>
'''
soup = BeautifulSoup(html)
使用BeautifulSoup解析这段代码,能够得到一个 BeautifulSoup 的对象,并能按照标准的缩进格式的结构输出。
1标准选择器
find_all
find_all(name,attrs,recursive,text,**kwargs)可以根据标签名,属性,内容查找文档
find
find(name,attrs,recursive,text,**kwargs)
find返回的匹配结果的第一个元素
结果返回的是一个列表的方式
soup.find_all(text=‘xx’)查询text=xx的文本
attrs可以传入字典的方式来查找标签,但是这里有个特殊的就是class,因为class在python中是特殊的字段,所以如果想要查找class相关的可以更改attrs={‘class_’:‘element’}或者soup.find_all(’’,{“class”:"element}),id等特殊的标签属性可以不写attrs。
2CSS选择器
通过select()直接传入CSS选择器就可以完成选择
[attr] 可以通过这种方法找到具有某个属性的所有标签
[atrr=xx] 例子[target=_blank]表示查找所有target=_blank的标签
get_text()可以获取文本内容
attrs获取属性