Python 爬蟲之Beautiful Soup模塊使用指南
爬取網(wǎng)頁(yè)的流程一般如下:
- 選著要爬的網(wǎng)址(url)
- 使用 python 登錄上這個(gè)網(wǎng)址(urlopen、requests 等)
- 讀取網(wǎng)頁(yè)信息(read() 出來(lái))
- 將讀取的信息放入 BeautifulSoup
- 使用 BeautifulSoup 選取 tag 信息等
可以看到,頁(yè)面的獲取其實(shí)不難,難的是數(shù)據(jù)的篩選,即如何獲取到自己想要的數(shù)據(jù)。本文就帶大家學(xué)習(xí)下 BeautifulSoup 的使用。
BeautifulSoup 官網(wǎng)介紹如下:
Beautiful Soup 是一個(gè)可以從 HTML 或 XML 文件中提取數(shù)據(jù)的 Python 庫(kù),它能夠通過(guò)你喜歡的轉(zhuǎn)換器實(shí)現(xiàn)慣用的文檔導(dǎo)航、查找、修改文檔的方式,能夠幫你節(jié)省數(shù)小時(shí)甚至數(shù)天的工作時(shí)間。
1 安裝
可以利用 pip 直接安裝:
$ pip install beautifulsoup4
BeautifulSoup 不僅支持 HTML 解析器,還支持一些第三方的解析器,如 lxml,XML,html5lib 但是需要安裝相應(yīng)的庫(kù)。如果我們不安裝,則 Python 會(huì)使用 Python 默認(rèn)的解析器,其中 lxml 解析器更加強(qiáng)大,速度更快,推薦安裝。
$ pip install html5lib $ pip install lxml
2 BeautifulSoup 的簡(jiǎn)單使用
首先我們先新建一個(gè)字符串,后面就以它來(lái)演示 BeautifulSoup 的使用。
html_doc = """ <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 rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" class="sister" id="link1">Elsie</a>, <a rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" class="sister" id="link2">Lacie</a> and <a rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" class="sister" id="link3">Tillie</a>; and they lived at the bottom of a well.</p> <p class="story">...</p> """
使用 BeautifulSoup 解析這段代碼,能夠得到一個(gè) BeautifulSoup 的對(duì)象,并能按照標(biāo)準(zhǔn)的縮進(jìn)格式的結(jié)構(gòu)輸出:
>>> from bs4 import BeautifulSoup >>> soup = BeautifulSoup(html_doc, "lxml") >>> print(soup.prettify())
篇幅有限,輸出結(jié)果這里不再展示。
另外,這里展示下幾個(gè)簡(jiǎn)單的瀏覽結(jié)構(gòu)化數(shù)據(jù)的方法:
>>> soup.title
<title>The Dormouse's story</title>
>>> soup.title.name
'title'
>>> soup.title.string
"The Dormouse's story"
>>> soup.p['class']
['title']
>>> soup.a
<a class="sister" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" id="link1">Elsie</a>
>>> soup.find_all('a')
[<a class="sister" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" id="link1">Elsie</a>, <a class="sister" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" id="link2">Lacie</a>, <a class="sister" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" id="link3">Tillie</a>]
>>> soup.find(id='link1')
<a class="sister" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" id="link1">Elsie</a>
3 對(duì)象的種類
Beautiful Soup 將復(fù)雜 HTML 文檔轉(zhuǎn)換成一個(gè)復(fù)雜的樹形結(jié)構(gòu),每個(gè)節(jié)點(diǎn)都是 Python 對(duì)象,所有對(duì)象可以歸納為 4 種: Tag、NavigableString、BeautifulSoup、Comment 。
3.1 Tag
Tag通俗點(diǎn)講就是 HTML 中的一個(gè)個(gè)標(biāo)簽,像上面的 div,p,例如:
<title>The Dormouse's story</title> <a class="sister" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" id="link1">Elsie</a>
可以利用 soup 加標(biāo)簽名輕松地獲取這些標(biāo)簽的內(nèi)容。
>>> print(soup.p) <p class="title"><b>The Dormouse's story</b></p> >>> print(soup.title) <title>The Dormouse's story</title>
不過(guò)有一點(diǎn)是,它查找的是在所有內(nèi)容中的第一個(gè)符合要求的標(biāo)簽,如果要查詢所有的標(biāo)簽,我們?cè)诤竺孢M(jìn)行介紹。
每個(gè) Tag 有兩個(gè)重要的屬性 name 和 attrs,name 指標(biāo)簽的名字或者 tag 本身的 name,attrs 通常指一個(gè)標(biāo)簽的 class。
>>> print(soup.p.name)
p
>>> print(soup.p.attrs)
{'class': ['title']}
3.2 NavigableString
NavigableString:獲取標(biāo)簽內(nèi)部的文字,如,soup.p.string。
>>> print(soup.p.string) The Dormouse's story
3.3 BeautifulSoup
BeautifulSoup:表示一個(gè)文檔的全部?jī)?nèi)容。大部分時(shí)候,可以把它當(dāng)作 Tag 對(duì)象,是一個(gè)特殊的 Tag。
3.4 Comment
Comment:Comment 對(duì)象是一個(gè)特殊類型的 NavigableString 對(duì)象,其輸出的內(nèi)容不包括注釋符號(hào),但是如果不好好處理它,可能會(huì)對(duì)我們的文本處理造成意想不到的麻煩。
>>> markup = "<b><!--Hey, buddy. Want to buy a used parser?--></b>" >>> soup = BeautifulSoup(markup) >>> comment = soup.b.string >>> print(comment) Hey, buddy. Want to buy a used parser? >>> type(comment) <class 'bs4.element.Comment'>
b 標(biāo)簽里的內(nèi)容實(shí)際上是注釋,但是如果我們利用 .string 來(lái)輸出它的內(nèi)容,我們發(fā)現(xiàn)它已經(jīng)把注釋符號(hào)去掉了,所以這可能會(huì)給我們帶來(lái)不必要的麻煩。
這時(shí)候我們可以先判斷了它的類型,是否為 bs4.element.Comment 類型,然后再進(jìn)行其他操作,如打印輸出等。
4 搜索文檔樹
BeautifulSoup 主要用來(lái)遍歷子節(jié)點(diǎn)及子節(jié)點(diǎn)的屬性,并提供了很多方法,比如獲取 子節(jié)點(diǎn)、父節(jié)點(diǎn)、兄弟節(jié)點(diǎn)等,但通過(guò)實(shí)踐來(lái)看,這些方法用到的并不多。我們主要用到的是從文檔樹中搜索出我們的目標(biāo)。
通過(guò)點(diǎn)取屬性的方式只能獲得當(dāng)前文檔中的第一個(gè) tag,例如,soup.li。如果想要得到所有的<li> 標(biāo)簽,就需要用到 find_all(),find_all() 方法搜索當(dāng)前 tag 的所有 tag 子節(jié)點(diǎn),并判斷是否符合過(guò)濾器的條件 find_all() 所接受的參數(shù)如下:
find_all( name , attrs , recursive , text , **kwargs )
4.1 按 name 搜索
可以查找所有名字為 name 的 tag,字符串對(duì)象會(huì)被自動(dòng)忽略掉。
>>> soup.find_all('b')
[<b>The Dormouse's story</b>]
>>> soup.find_all('a')
[<a class="sister" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" id="link1">Elsie</a>, <a class="sister" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" id="link2">Lacie</a>, <a class="sister" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" id="link3">Tillie</a>]
4.2 按 id 搜索
如果文檔樹中包含一個(gè)名字為 id 的參數(shù),其實(shí)在搜索時(shí)會(huì)把該參數(shù)當(dāng)作指定名字 tag 的屬性來(lái)搜索:
>>> soup.find_all(id='link1') [<a class="sister" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" id="link1">Elsie</a>]
4.3 按 attr 搜索
有些 tag 屬性在搜索不能使用,比如 HTML5 中的 data-* 屬性,但是可以通過(guò) find_all() 方法的 attrs 參數(shù)定義一個(gè)字典參數(shù)來(lái)搜索包含特殊屬性的 tag。
其實(shí) id 也是一個(gè) attr:
>>> soup.find_all(attrs={'id':'link1'})
[<a class="sister" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" id="link1">Elsie</a>]
4.4 按 CSS 搜索
按照 CSS 類名搜索 tag 的功能非常實(shí)用,但標(biāo)識(shí) CSS 類名的關(guān)鍵字 class 在 Python 中是保留字,使用 class 做參數(shù)會(huì)導(dǎo)致語(yǔ)法錯(cuò)誤。因此從 Beautiful Soup 的 4.1.1 版本開(kāi)始,可以通過(guò) class_ 參數(shù)搜索有指定 CSS 類名的 tag:
>>> soup.find_all(class_='sister') [<a class="sister" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" id="link1">Elsie</a>, <a class="sister" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" id="link2">Lacie</a>, <a class="sister" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" id="link3">Tillie</a>]
4.5 string 參數(shù)
通過(guò) string 參數(shù)可以搜搜文檔中的字符串內(nèi)容。與 name 參數(shù)的可選值一樣,string 參數(shù)接受字符串、正則表達(dá)式、列表、True。
>>> soup.find_all('a', string='Elsie')
[<a class="sister" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" id="link1">Elsie</a>]
4.6 recursive 參數(shù)
調(diào)用 tag 的 find_all() 方法時(shí),Beautiful Soup 會(huì)檢索當(dāng)前 tag 的所有子孫節(jié)點(diǎn),如果只想搜索 tag 的直接子節(jié)點(diǎn),可以使用參數(shù) recursive=False。
4.6 find() 方法
它與 find_all() 方法唯一的區(qū)別是 find_all() 方法的返回結(jié)果是值包含一個(gè)元素的列表,而 find() 方法只返回第一個(gè)匹配的結(jié)果。
4.7 get_text() 方法
如果只想得到 tag 中包含的文本內(nèi)容,那么可以用 get_text() 方法,這個(gè)方法獲取到 tag 中包含的所有文本內(nèi)容。
>>> soup.find_all('a', string='Elsie')[0].get_text()
'Elsie'
>>> soup.find_all('a', string='Elsie')[0].string
'Elsie'
至此,Beautiful Soup 的常用使用方法已講完,若果想了解更多內(nèi)容,建議看下官方文檔:https://www.crummy.com/software/BeautifulSoup/bs4/doc.zh/。
總結(jié)
本篇主要帶大家了解了 Beautiful Soup,結(jié)合一些小例子,相信大家對(duì) Beautiful Soup 已不再陌生,下回會(huì)帶大家結(jié)合 Beautiful Soup 進(jìn)行爬蟲的實(shí)戰(zhàn),歡迎繼續(xù)關(guān)注!
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- Python爬蟲實(shí)現(xiàn)使用beautifulSoup4爬取名言網(wǎng)功能案例
- Python BeautifulSoup [解決方法] TypeError: list indices must be integers or slices, not str
- python中bs4.BeautifulSoup的基本用法
- Python爬蟲beautifulsoup4常用的解析方法總結(jié)
- python3解析庫(kù)BeautifulSoup4的安裝配置與基本用法
- python3第三方爬蟲庫(kù)BeautifulSoup4安裝教程
- Python爬蟲包BeautifulSoup簡(jiǎn)介與安裝(一)
- python使用beautifulsoup4爬取酷狗音樂(lè)代碼實(shí)例
相關(guān)文章
Python實(shí)現(xiàn)內(nèi)網(wǎng)穿透和端口轉(zhuǎn)發(fā)代理詳解
這篇文章主要為大家介紹了Python實(shí)現(xiàn)內(nèi)網(wǎng)穿透和端口轉(zhuǎn)發(fā)代理詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-12-12
Python使用Flask框架同時(shí)上傳多個(gè)文件的方法
這篇文章主要介紹了Python使用Flask框架同時(shí)上傳多個(gè)文件的方法,實(shí)例分析了Python中Flask框架操作文件實(shí)現(xiàn)上傳的技巧,需要的朋友可以參考下2015-03-03
Python調(diào)用百度api實(shí)現(xiàn)語(yǔ)音識(shí)別詳解
這篇文章主要介紹了Python通過(guò)調(diào)用百度api實(shí)現(xiàn)語(yǔ)音識(shí)別,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)吧2021-12-12
詳解LyScript 內(nèi)存掃描與查殼實(shí)現(xiàn)
這篇文章主要為大家介紹了詳解LyScript 內(nèi)存掃描與查殼實(shí)現(xiàn)詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-09-09
python+Django實(shí)現(xiàn)防止SQL注入的辦法
這篇文章主要介紹了python+Django實(shí)現(xiàn)防止SQL注入的辦法,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-10-10
python中dropna()函數(shù)的作用舉例說(shuō)明
這篇文章主要給大家介紹了關(guān)于python中dropna()函數(shù)的相關(guān)資料,dropna()是pandas庫(kù)中的一個(gè)函數(shù),用于刪除DataFrame中的缺失值,文中通過(guò)代碼介紹的非常詳細(xì),需要的朋友可以參考下2023-11-11

