(2018-05-18.Python從Zero到One)2、(爬蟲)非結(jié)構(gòu)化數(shù)據(jù)與結(jié)構(gòu)化數(shù)據(jù)提取__1.2.5BeautifulSoup4解析器

CSS 選擇器:BeautifulSoup4

和 lxml 一樣钞诡,Beautiful Soup 也是一個HTML/XML的解析器郑现,主要的功能也是如何解析和提取 HTML/XML 數(shù)據(jù)湃崩。

lxml 只會局部遍歷,而Beautiful Soup 是基于HTML DOM的接箫,會載入整個文檔攒读,解析整個DOM樹,因此時間和內(nèi)存開銷都會大很多辛友,所以性能要低于lxml薄扁。

BeautifulSoup 用來解析 HTML 比較簡單,API非常人性化废累,支持CSS選擇器邓梅、Python標(biāo)準(zhǔn)庫中的HTML解析器,也支持 lxml 的 XML解析器邑滨。

Beautiful Soup 3 目前已經(jīng)停止開發(fā)日缨,推薦現(xiàn)在的項目使用Beautiful Soup 4。使用 pip 安裝即可:pip install beautifulsoup4

官方文檔:http://beautifulsoup.readthedocs.io/zh_CN/v4.4.0

抓取工具 速度 使用難度 安裝難度
正則 最快 困難 無(內(nèi)置)
BeautifulSoup 最簡單 簡單
lxml 簡單 一般

示例:

首先必須要導(dǎo)入 bs4 庫

# beautifulsoup4_test.py

from bs4 import BeautifulSoup

html = """
<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 對象
soup = BeautifulSoup(html)

#打開本地 HTML 文件的方式來創(chuàng)建對象
#soup = BeautifulSoup(open('index.html'))

#格式化輸出 soup 對象的內(nèi)容
print soup.prettify()

運行結(jié)果:

<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>
 </body>
</html>

  • 如果我們在 IPython2 下執(zhí)行掖看,會看到這樣一段警告:
    day52_爬蟲-非結(jié)構(gòu)化數(shù)據(jù)與結(jié)構(gòu)化數(shù)據(jù)提取-01.png
  • 意思是匣距,如果我們沒有顯式地指定解析器,所以默認(rèn)使用這個系統(tǒng)的最佳可用HTML解析器(“l(fā)xml”)哎壳。如果你在另一個系統(tǒng)中運行這段代碼毅待,或者在不同的虛擬環(huán)境中,使用不同的解析器造成行為不同归榕。
  • 但是我們可以通過soup = BeautifulSoup(html,“l(fā)xml”)方式指定lxml解析器猬错。

四大對象種類

Beautiful Soup將復(fù)雜HTML文檔轉(zhuǎn)換成一個復(fù)雜的樹形結(jié)構(gòu),每個節(jié)點都是Python對象,所有對象可以歸納為4種:

  • Tag
  • NavigableString
  • BeautifulSoup
  • Comment

1. Tag

Tag 通俗點講就是 HTML 中的一個個標(biāo)簽漂问,例如:

<head><title>The Dormouse's story</title></head>
<a class="sister"  id="link1"><!-- Elsie --></a>
<p class="title" name="dromouse"><b>The Dormouse's story</b></p>

上面的 title head a p等等 HTML 標(biāo)簽加上里面包括的內(nèi)容就是 Tag狼犯,那么試著使用 Beautiful Soup 來獲取 Tags:

from bs4 import BeautifulSoup

html = """
<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 對象
soup = BeautifulSoup(html)

print soup.title
# <title>The Dormouse's story</title>

print soup.head
# <head><title>The Dormouse's story</title></head>

print soup.a
# <a class="sister"  id="link1"><!-- Elsie --></a>

print soup.p
# <p class="title" name="dromouse"><b>The Dormouse's story</b></p>

print type(soup.p)
# <class 'bs4.element.Tag'>

我們可以利用 soup 加標(biāo)簽名輕松地獲取這些標(biāo)簽的內(nèi)容疏虫,這些對象的類型是bs4.element.Tag。但是注意循签,它查找的是在所有內(nèi)容中的第一個符合要求的標(biāo)簽级乐。如果要查詢所有的標(biāo)簽,后面會進行介紹县匠。

對于 Tag,它有兩個重要的屬性撒轮,是 name 和 attrs
print soup.name
# [document] #soup 對象本身比較特殊乞旦,它的 name 即為 [document]

print soup.head.name
# head #對于其他內(nèi)部標(biāo)簽,輸出的值便為標(biāo)簽本身的名稱

print soup.p.attrs
# {'class': ['title'], 'name': 'dromouse'}
# 在這里题山,我們把 p 標(biāo)簽的所有屬性打印輸出了出來兰粉,得到的類型是一個字典。

print soup.p['class'] # soup.p.get('class')
# ['title'] #還可以利用get方法顶瞳,傳入屬性的名稱玖姑,二者是等價的

soup.p['class'] = "newClass"
print soup.p # 可以對這些屬性和內(nèi)容等等進行修改
# <p class="newClass" name="dromouse"><b>The Dormouse's story</b></p>

del soup.p['class'] # 還可以對這個屬性進行刪除
print soup.p
# <p name="dromouse"><b>The Dormouse's story</b></p>

2. NavigableString

既然我們已經(jīng)得到了標(biāo)簽的內(nèi)容愕秫,那么問題來了,我們要想獲取標(biāo)簽內(nèi)部的文字怎么辦呢焰络?很簡單戴甩,用 .string 即可,例如

print soup.p.string
# The Dormouse's story

print type(soup.p.string)
# In [13]: <class 'bs4.element.NavigableString'>

3. BeautifulSoup

BeautifulSoup 對象表示的是一個文檔的內(nèi)容闪彼。大部分時候,可以把它當(dāng)作 Tag 對象甜孤,是一個特殊的 Tag,我們可以分別獲取它的類型畏腕,名稱缴川,以及屬性來感受一下

print type(soup.name)
# <type 'unicode'>

print soup.name 
# [document]

print soup.attrs # 文檔本身的屬性為空
# {}

4. Comment

Comment 對象是一個特殊類型的 NavigableString 對象,其輸出的內(nèi)容不包括注釋符號描馅。

print soup.a
# <a class="sister"  id="link1"><!-- Elsie --></a>

print soup.a.string
# Elsie 

print type(soup.a.string)
# <class 'bs4.element.Comment'>

a 標(biāo)簽里的內(nèi)容實際上是注釋把夸,但是如果我們利用 .string 來輸出它的內(nèi)容時,注釋符號已經(jīng)去掉了铭污。

遍歷文檔樹

1. 直接子節(jié)點 :.contents``.children 屬性

.content

tag 的 .content 屬性可以將tag的子節(jié)點以列表的方式輸出

print soup.head.contents 
#[<title>The Dormouse's story</title>]

輸出方式為列表扎即,我們可以用列表索引來獲取它的某一個元素

print soup.head.contents[0]
#<title>The Dormouse's story</title>

.children

它返回的不是一個 list,不過我們可以通過遍歷獲取所有子節(jié)點况凉。

我們打印輸出 .children 看一下谚鄙,可以發(fā)現(xiàn)它是一個 list 生成器對象

print soup.head.children
#<listiterator object at 0x7f71457f5710>

for child in  soup.body.children:
    print child

結(jié)果:

<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>

2. 所有子孫節(jié)點: .descendants 屬性

.contents 和 .children 屬性僅包含tag的直接子節(jié)點,.descendants 屬性可以對所有tag的子孫節(jié)點進行遞歸循環(huán)刁绒,和 children類似闷营,我們也需要遍歷獲取其中的內(nèi)容。

for child in soup.descendants:
    print child

運行結(jié)果:

<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>
</body></html>
<head><title>The Dormouse's story</title></head>
<title>The Dormouse's story</title>
The Dormouse's story

<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>
</body>

<p class="title" name="dromouse"><b>The Dormouse's story</b></p>
<b>The Dormouse's story</b>
The Dormouse's story

<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>
Once upon a time there were three little sisters; and their names were

<a class="sister"  id="link1"><!-- Elsie --></a>
 Elsie 
,

<a class="sister"  id="link2">Lacie</a>
Lacie
 and

<a class="sister"  id="link3">Tillie</a>
Tillie
;
and they lived at the bottom of a well.

<p class="story">...</p>
...

3. 節(jié)點內(nèi)容: .string 屬性

如果tag只有一個 NavigableString 類型子節(jié)點,那么這個tag可以使用 .string 得到子節(jié)點知市。如果一個tag僅有一個子節(jié)點,那么這個tag也可以使用 .string 方法,輸出結(jié)果與當(dāng)前唯一子節(jié)點的 .string 結(jié)果相同傻盟。

通俗點說就是:如果一個標(biāo)簽里面沒有標(biāo)簽了,那么 .string 就會返回標(biāo)簽里面的內(nèi)容嫂丙。如果標(biāo)簽里面只有唯一的一個標(biāo)簽了娘赴,那么 .string 也會返回最里面的內(nèi)容。例如:

print soup.head.string
#The Dormouse's story
print soup.title.string
#The Dormouse's story

搜索文檔樹

1.find_all(name, attrs, recursive, text, **kwargs)

1)name 參數(shù)

name 參數(shù)可以查找所有名字為 name 的tag,字符串對象會被自動忽略掉

A.傳字符串

最簡單的過濾器是字符串.在搜索方法中傳入一個字符串參數(shù),Beautiful Soup會查找與字符串完整匹配的內(nèi)容,下面的例子用于查找文檔中所有的<b>標(biāo)簽:

soup.find_all('b')
# [<b>The Dormouse's story</b>]

print soup.find_all('a')
#[<a class="sister"  id="link1"><!-- Elsie --></a>, <a class="sister"  id="link2">Lacie</a>, <a class="sister"  id="link3">Tillie</a>]

B.傳正則表達式

如果傳入正則表達式作為參數(shù),Beautiful Soup會通過正則表達式的 match() 來匹配內(nèi)容.下面例子中找出所有以b開頭的標(biāo)簽,這表示<body><b>標(biāo)簽都應(yīng)該被找到

import re
for tag in soup.find_all(re.compile("^b")):
    print(tag.name)
# body
# b

C.傳列表

如果傳入列表參數(shù),Beautiful Soup會將與列表中任一元素匹配的內(nèi)容返回.下面代碼找到文檔中所有<a>標(biāo)簽和<b>標(biāo)簽:

soup.find_all(["a", "b"])
# [<b>The Dormouse's story</b>,
#  <a class="sister"  id="link1">Elsie</a>,
#  <a class="sister"  id="link2">Lacie</a>,
#  <a class="sister"  id="link3">Tillie</a>]

2)keyword 參數(shù)

soup.find_all(id='link2')
# [<a class="sister"  id="link2">Lacie</a>]

3)text 參數(shù)

通過 text 參數(shù)可以搜搜文檔中的字符串內(nèi)容跟啤,與 name 參數(shù)的可選值一樣, text 參數(shù)接受 字符串 , 正則表達式 , 列表

soup.find_all(text="Elsie")
# [u'Elsie']

soup.find_all(text=["Tillie", "Elsie", "Lacie"])
# [u'Elsie', u'Lacie', u'Tillie']

soup.find_all(text=re.compile("Dormouse"))
[u"The Dormouse's story", u"The Dormouse's story"]

CSS選擇器

這就是另一種與 find_all 方法有異曲同工之妙的查找方法.

  • 寫 CSS 時诽表,標(biāo)簽名不加任何修飾,類名前加.隅肥,id名前加#

  • 在這里我們也可以利用類似的方法來篩選元素竿奏,用到的方法是 soup.select(),返回類型是 list

(1)通過標(biāo)簽名查找

print soup.select('title') 
#[<title>The Dormouse's story</title>]

print soup.select('a')
#[<a class="sister"  id="link1"><!-- Elsie --></a>, <a class="sister"  id="link2">Lacie</a>, <a class="sister"  id="link3">Tillie</a>]

print soup.select('b')
#[<b>The Dormouse's story</b>]

(2)通過類名查找

print soup.select('.sister')
#[<a class="sister"  id="link1"><!-- Elsie --></a>, <a class="sister"  id="link2">Lacie</a>, <a class="sister"  id="link3">Tillie</a>]

(3)通過 id 名查找

print soup.select('#link1')
#[<a class="sister"  id="link1"><!-- Elsie --></a>]

(4)組合查找

組合查找即和寫 class 文件時腥放,標(biāo)簽名與類名泛啸、id名進行的組合原理是一樣的,例如查找 p 標(biāo)簽中秃症,id 等于 link1的內(nèi)容候址,二者需要用空格分開

print soup.select('p #link1')
#[<a class="sister"  id="link1"><!-- Elsie --></a>]

直接子標(biāo)簽查找吕粹,則使用 > 分隔

print soup.select("head > title")
#[<title>The Dormouse's story</title>]

(5)屬性查找

查找時還可以加入屬性元素,屬性需要用中括號括起來岗仑,注意屬性和標(biāo)簽屬于同一節(jié)點匹耕,所以中間不能加空格,否則會無法匹配到赔蒲。

print soup.select('a[class="sister"]')
#[<a class="sister"  id="link1"><!-- Elsie --></a>, <a class="sister"  id="link2">Lacie</a>, <a class="sister"  id="link3">Tillie</a>]

print soup.select('a[)
#[<a class="sister"  id="link1"><!-- Elsie --></a>]

同樣泌神,屬性仍然可以與上述查找方式組合,不在同一節(jié)點的空格隔開舞虱,同一節(jié)點的不加空格

print soup.select('p a[)
#[<a class="sister"  id="link1"><!-- Elsie --></a>]

(6) 獲取內(nèi)容

以上的 select 方法返回的結(jié)果都是列表形式欢际,可以遍歷形式輸出,然后用 get_text() 方法來獲取它的內(nèi)容矾兜。

soup = BeautifulSoup(html, 'lxml')
print type(soup.select('title'))
print soup.select('title')[0].get_text()

for title in soup.select('title'):
    print title.get_text()
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末损趋,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子椅寺,更是在濱河造成了極大的恐慌浑槽,老刑警劉巖,帶你破解...
    沈念sama閱讀 216,997評論 6 502
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件返帕,死亡現(xiàn)場離奇詭異桐玻,居然都是意外死亡,警方通過查閱死者的電腦和手機荆萤,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,603評論 3 392
  • 文/潘曉璐 我一進店門镊靴,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人链韭,你說我怎么就攤上這事偏竟。” “怎么了敞峭?”我有些...
    開封第一講書人閱讀 163,359評論 0 353
  • 文/不壞的土叔 我叫張陵踊谋,是天一觀的道長。 經(jīng)常有香客問我旋讹,道長殖蚕,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,309評論 1 292
  • 正文 為了忘掉前任骗村,我火速辦了婚禮嫌褪,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘胚股。我一直安慰自己,他們只是感情好裙秋,可當(dāng)我...
    茶點故事閱讀 67,346評論 6 390
  • 文/花漫 我一把揭開白布琅拌。 她就那樣靜靜地躺著缨伊,像睡著了一般。 火紅的嫁衣襯著肌膚如雪进宝。 梳的紋絲不亂的頭發(fā)上刻坊,一...
    開封第一講書人閱讀 51,258評論 1 300
  • 那天,我揣著相機與錄音党晋,去河邊找鬼谭胚。 笑死,一個胖子當(dāng)著我的面吹牛未玻,可吹牛的內(nèi)容都是我干的灾而。 我是一名探鬼主播,決...
    沈念sama閱讀 40,122評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼扳剿,長吁一口氣:“原來是場噩夢啊……” “哼旁趟!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起庇绽,我...
    開封第一講書人閱讀 38,970評論 0 275
  • 序言:老撾萬榮一對情侶失蹤锡搜,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后瞧掺,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體耕餐,經(jīng)...
    沈念sama閱讀 45,403評論 1 313
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,596評論 3 334
  • 正文 我和宋清朗相戀三年辟狈,在試婚紗的時候發(fā)現(xiàn)自己被綠了肠缔。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 39,769評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡上陕,死狀恐怖桩砰,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情释簿,我是刑警寧澤亚隅,帶...
    沈念sama閱讀 35,464評論 5 344
  • 正文 年R本政府宣布,位于F島的核電站庶溶,受9級特大地震影響煮纵,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜偏螺,卻給世界環(huán)境...
    茶點故事閱讀 41,075評論 3 327
  • 文/蒙蒙 一行疏、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧套像,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,705評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽喳张。三九已至,卻和暖如春销部,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背舅桩。 一陣腳步聲響...
    開封第一講書人閱讀 32,848評論 1 269
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留江咳,地道東北人逢净。 一個月前我還...
    沈念sama閱讀 47,831評論 2 370
  • 正文 我出身青樓,卻偏偏與公主長得像歼指,于是被迫代替她去往敵國和親爹土。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,678評論 2 354

推薦閱讀更多精彩內(nèi)容