和 lxml 一樣律歼,Beautiful Soup 也是一個(gè)HTML/XML的解析器民镜,主要的功能也是如何解析和提取 HTML/XML 數(shù)據(jù)。
lxml 只會(huì)局部遍歷险毁,而B(niǎo)eautiful Soup 是基于HTML DOM(Document Object Model)的制圈,會(huì)載入整個(gè)文檔,解析整個(gè)DOM樹(shù)畔况,因此時(shí)間和內(nèi)存開(kāi)銷(xiāo)都會(huì)大很多鲸鹦,所以性能要低于lxml。
BeautifulSoup 用來(lái)解析 HTML 比較簡(jiǎn)單跷跪,API非常人性化馋嗜,支持CSS選擇器、Python標(biāo)準(zhǔn)庫(kù)中的HTML解析器吵瞻,也支持 lxml 的 XML解析器葛菇。
Beautiful Soup 3 目前已經(jīng)停止開(kāi)發(fā)甘磨,推薦現(xiàn)在的項(xiàng)目使用Beautiful Soup 4。
安裝和文檔:
安裝:pip install bs4。
中文文檔:https://www.crummy.com/software/BeautifulSoup/bs4/doc/index.zh.html
Pycharm激活碼教程使用更多解釋請(qǐng)見(jiàn):http://vrg123.com
幾大解析工具對(duì)比:
解析工具解析速度使用難度
BeautifulSoup最慢最簡(jiǎn)單
lxml快簡(jiǎn)單
正則最快最難
簡(jiǎn)單使用:
frombs4importBeautifulSouphtml ="""
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title" name="dromouse"><b>The Dormouse's story</b></p>
<p class="story">Once upon a time there were three little sisters; and their names were
<a class="sister" id="link1"><!-- Elsie --></a>,
<a class="sister" id="link2">Lacie</a> and
<a class="sister" id="link3">Tillie</a>;
and they lived at the bottom of a well.</p>
<p class="story">...</p>
"""#創(chuàng)建 Beautiful Soup 對(duì)象# 使用lxml來(lái)進(jìn)行解析soup = BeautifulSoup(html,"lxml")print(soup.prettify())
四個(gè)常用的對(duì)象:
Beautiful Soup將復(fù)雜HTML文檔轉(zhuǎn)換成一個(gè)復(fù)雜的樹(shù)形結(jié)構(gòu),每個(gè)節(jié)點(diǎn)都是Python對(duì)象,所有對(duì)象可以歸納為4種:
Tag
NavigatableString
BeautifulSoup
Comment
1. Tag:
Tag 通俗點(diǎn)講就是 HTML 中的一個(gè)個(gè)標(biāo)簽。示例代碼如下:
frombs4importBeautifulSouphtml ="""
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title" name="dromouse"><b>The Dormouse's story</b></p>
<p class="story">Once upon a time there were three little sisters; and their names were
<a class="sister" id="link1"><!-- Elsie --></a>,
<a class="sister" id="link2">Lacie</a> and
<a class="sister" id="link3">Tillie</a>;
and they lived at the bottom of a well.</p>
<p class="story">...</p>
"""#創(chuàng)建 Beautiful Soup 對(duì)象soup = BeautifulSoup(html,'lxml')printsoup.title# <title>The Dormouse's story</title>printsoup.head# <head><title>The Dormouse's story</title></head>printsoup.a# <a class="sister" id="link1"><!-- Elsie --></a>printsoup.p# <p class="title" name="dromouse"><b>The Dormouse's story</b></p>printtype(soup.p)# <class 'bs4.element.Tag'>
我們可以利用 soup 加標(biāo)簽名輕松地獲取這些標(biāo)簽的內(nèi)容驹针,這些對(duì)象的類(lèi)型是bs4.element.Tag摔寨。但是注意,它查找的是在所有內(nèi)容中的第一個(gè)符合要求的標(biāo)簽缓艳。如果要查詢(xún)所有的標(biāo)簽,后面會(huì)進(jìn)行介紹。
對(duì)于Tag椎瘟,它有兩個(gè)重要的屬性,分別是name和attrs侄旬。示例代碼如下:
printsoup.name# [document] #soup 對(duì)象本身比較特殊肺蔚,它的 name 即為 [document]printsoup.head.name# head #對(duì)于其他內(nèi)部標(biāo)簽,輸出的值便為標(biāo)簽本身的名稱(chēng)printsoup.p.attrs# {'class': ['title'], 'name': 'dromouse'}# 在這里儡羔,我們把 p 標(biāo)簽的所有屬性打印輸出了出來(lái)宣羊,得到的類(lèi)型是一個(gè)字典。printsoup.p['class']# soup.p.get('class')# ['title'] #還可以利用get方法汰蜘,傳入屬性的名稱(chēng)仇冯,二者是等價(jià)的soup.p['class'] ="newClass"printsoup.p# 可以對(duì)這些屬性和內(nèi)容等等進(jìn)行修改# <p class="newClass" name="dromouse"><b>The Dormouse's story</b></p>
2. NavigableString:
如果拿到標(biāo)簽后,還想獲取標(biāo)簽中的內(nèi)容族操。那么可以通過(guò)tag.string獲取標(biāo)簽中的文字苛坚。示例代碼如下:
printsoup.p.string# The Dormouse's storyprinttype(soup.p.string)# <class 'bs4.element.NavigableString'>thon
3. BeautifulSoup:
BeautifulSoup 對(duì)象表示的是一個(gè)文檔的全部?jī)?nèi)容.大部分時(shí)候,可以把它當(dāng)作 Tag 對(duì)象,它支持 遍歷文檔樹(shù) 和 搜索文檔樹(shù) 中描述的大部分的方法.
因?yàn)?BeautifulSoup 對(duì)象并不是真正的HTML或XML的tag,所以它沒(méi)有name和attribute屬性.但有時(shí)查看它的 .name 屬性是很方便的,所以 BeautifulSoup 對(duì)象包含了一個(gè)值為 “[document]” 的特殊屬性 .name
soup.name# '[document]'
4. Comment:
Tag , NavigableString , BeautifulSoup 幾乎覆蓋了html和xml中的所有內(nèi)容,但是還有一些特殊對(duì)象.容易讓人擔(dān)心的內(nèi)容是文檔的注釋部分:
markup ="<b><!--Hey, buddy. Want to buy a used parser?--></b>"soup = BeautifulSoup(markup)comment = soup.b.stringtype(comment)# <class 'bs4.element.Comment'>
Comment 對(duì)象是一個(gè)特殊類(lèi)型的 NavigableString 對(duì)象:
comment# 'Hey, buddy. Want to buy a used parser'
遍歷文檔樹(shù):
1. contents和children:
html_doc ="""
<html><head><title>The Dormouse's story</title></head>
<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 class="sister" id="link1">Elsie</a>,
<a class="sister" id="link2">Lacie</a> and
<a class="sister" id="link3">Tillie</a>;
and they lived at the bottom of a well.</p>
<p class="story">...</p>
"""frombs4importBeautifulSoupsoup = BeautifulSoup(html_doc,'lxml')head_tag = soup.head# 返回所有子節(jié)點(diǎn)的列表print(head_tag.contents)# 返回所有子節(jié)點(diǎn)的迭代器forchildinhead_tag.children:? ? print(child)
2. strings 和 stripped_strings
如果tag中包含多個(gè)字符串 [2] ,可以使用 .strings 來(lái)循環(huán)獲取:
forstringinsoup.strings:? ? print(repr(string))# u"The Dormouse's story"# u'\n\n'# u"The Dormouse's story"# u'\n\n'# u'Once upon a time there were three little sisters; and their names were\n'# u'Elsie'# u',\n'# u'Lacie'# u' and\n'# u'Tillie'# u';\nand they lived at the bottom of a well.'# u'\n\n'# u'...'# u'\n'
輸出的字符串中可能包含了很多空格或空行,使用 .stripped_strings 可以去除多余空白內(nèi)容:
forstringinsoup.stripped_strings:? ? print(repr(string))# u"The Dormouse's story"# u"The Dormouse's story"# u'Once upon a time there were three little sisters; and their names were'# u'Elsie'# u','# u'Lacie'# u'and'# u'Tillie'# u';\nand they lived at the bottom of a well.'# u'...'
搜索文檔樹(shù):
1. find和find_all方法:
搜索文檔樹(shù)色难,一般用得比較多的就是兩個(gè)方法泼舱,一個(gè)是find,一個(gè)是find_all枷莉。find方法是找到第一個(gè)滿(mǎn)足條件的標(biāo)簽后就立即返回娇昙,只返回一個(gè)元素。find_all方法是把所有滿(mǎn)足條件的標(biāo)簽都選到笤妙,然后返回回去冒掌。使用這兩個(gè)方法,最常用的用法是出入name以及attr參數(shù)找出符合要求的標(biāo)簽蹲盘。
soup.find_all("a",attrs={"id":"link2"})
或者是直接傳入屬性的的名字作為關(guān)鍵字參數(shù):
soup.find_all("a",id='link2')
2. select方法:
使用以上方法可以方便的找出元素宋渔。但有時(shí)候使用css選擇器的方式可以更加的方便。使用css選擇器的語(yǔ)法辜限,應(yīng)該使用select方法皇拣。以下列出幾種常用的css選擇器方法:
(1)通過(guò)標(biāo)簽名查找:
print(soup.select('a'))
(2)通過(guò)類(lèi)名查找:
通過(guò)類(lèi)名,則應(yīng)該在類(lèi)的前面加一個(gè).。比如要查找class=sister的標(biāo)簽氧急。示例代碼如下:
print(soup.select('.sister'))
(3)通過(guò)id查找:
通過(guò)id查找颗胡,應(yīng)該在id的名字前面加一個(gè)#號(hào)。示例代碼如下:
print(soup.select("#link1"))
(4)組合查找:
組合查找即和寫(xiě) class 文件時(shí)吩坝,標(biāo)簽名與類(lèi)名毒姨、id名進(jìn)行的組合原理是一樣的,例如查找 p 標(biāo)簽中钉寝,id 等于 link1的內(nèi)容弧呐,二者需要用空格分開(kāi):
print(soup.select("p #link1"))
直接子標(biāo)簽查找,則使用 > 分隔:
print(soup.select("head > title"))
(5)通過(guò)屬性查找:
查找時(shí)還可以加入屬性元素嵌纲,屬性需要用中括號(hào)括起來(lái)俘枫,注意屬性和標(biāo)簽屬于同一節(jié)點(diǎn),所以中間不能加空格逮走,否則會(huì)無(wú)法匹配到鸠蚪。示例代碼如下:
print(soup.select('a[))
(6)獲取內(nèi)容
以上的 select 方法返回的結(jié)果都是列表形式,可以遍歷形式輸出师溅,然后用 get_text() 方法來(lái)獲取它的內(nèi)容茅信。
soup = BeautifulSoup(html,'lxml')printtype(soup.select('title'))printsoup.select('title')[0].get_text()fortitleinsoup.select('title'):printtitle.get_text()