CSS選擇器:BeautifulSoup4
和lxml一樣,Beautiful Soup也是一個(gè)HTML/XML的解析器,主要的功能也是如何解析和提取HTML/XML數(shù)據(jù)。
lxml只會(huì)局部遍歷,而B(niǎo)eautiful Soup是基于HTML DOM的,會(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 Soup3目前已經(jīng)停止開(kāi)發(fā),推薦現(xiàn)在的項(xiàng)目使用Beautiful Soup。使用pip安裝即可:pip install beautifulsoup4
| 抓取工具 | 速度 | 使用難道 | 安裝難度 |
|---|---|---|---|
| 正則 | 最快 | 困難 | 無(wú)(內(nèi)置) |
| BeautifulSoup | 慢 | 最簡(jiǎn)單 | 簡(jiǎn)單 |
| lxml | 快 | 簡(jiǎn)單 | 一般 |
官方文檔: http://beautifulsoup.readthedocs.io/zh_CN/v4.4.0
| 抓取工具 | 速度 | 使用難道 | 安裝難度 |
|---|---|---|---|
| 正則 | 最快 | 困難 | 無(wú)(內(nèi)置) |
| BeautifulSoup | 慢 | 最簡(jiǎn)單 | 簡(jiǎn)單 |
| lxml | 快 | 簡(jiǎn)單 | 一般 |
實(shí)例:
首先必須要導(dǎo)入bs4庫(kù)
# 07-urllib2_beautipulsoup_prettify
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 對(duì)象
soup = BeautifulSoup(html)
#打開(kāi)本地 HTML 文件的方式來(lái)創(chuàng)建對(duì)象
#soup = BeautifulSoup(open('index.html'))
#格式化輸出 soup 對(duì)象的內(nèi)容
print soup.prettify()
運(yùn)行結(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>
如果我們?cè)贗Python2下執(zhí)行,會(huì)看到這樣一段警告:
bs4警告- 意思是,如果我們沒(méi)有顯示地指定解析器,所以默認(rèn)使用這個(gè)系統(tǒng)的最佳可用HTML解析器("lxml")。如果你在另一個(gè)系統(tǒng)中運(yùn)行這段代碼,或者在不同的虛擬環(huán)境中,使用不同的解析器造成行為不同。
- 但是我們可以通過(guò)
soup = BeautifulSoup(html, "lxml")
四大對(duì)象種類(lèi)
Beautiful Soup將復(fù)雜HTML文檔轉(zhuǎn)換成一個(gè)復(fù)雜的樹(shù)形結(jié)構(gòu),每個(gè)節(jié)點(diǎn)都是Python對(duì)象,所有對(duì)象可以歸納為4種:
- Tag
- NaviganleString
- BeautifulSoup
- Comment
1.Tag
Tag通俗點(diǎn)講就是HTM中的一個(gè)個(gè)標(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等等標(biāo)簽上加上里面包括的內(nèi)容就是Tag,那么試著使用Beautiful Soup來(lái)獲取Tags
#-*- coding:utf-8 -*-
#08-urllib2_beautifulsoup_tag.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對(duì)象
soup = BeautifulSoup(html)
print soup.title
#<title>The Dormouse's story</title>
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)容,這些對(duì)象的類(lèi)型是bs4.element.Tag。但是注意,它查找的是在所有內(nèi)容中的第一個(gè)符合要求的標(biāo)簽。如果要查詢所有的標(biāo)簽,后面會(huì)進(jìn)行介紹。
對(duì)于Tag,它有兩個(gè)重要的屬性,是name和attrs
print soup.name
#[document] #soup對(duì)象本身比較特殊,它的name即為[document]
print soup.head.name
#head #對(duì)于其他內(nèi)部標(biāo)簽,輸出的值便為標(biāo)簽本身的名稱
print soup.p.attrs
#{'class':['title'], 'name':'dromouse'}
#在這里,我們把p標(biāo)簽的所有屬性打印出來(lái),得到的類(lèi)型是一個(gè)字典
print soup.p['class'] #soup.p.get('class')
#['title'] #還可以利用get方法,傳入屬性的方法,二者是等價(jià)的。
soup.a['class'] = 'newClass'
print soup.p #可以對(duì)這些屬性和內(nèi)容等等進(jìn)行修改
# <p class="newClass" name="dromouse"><b>The Dormouse's story</b></p>
del soup.p['class'] #還可以對(duì)這個(gè)屬性進(jìn)行刪除
print soup.p
# <p name="dromouse"><b>The Dormouse's story</b></p>
2. NavigableString
既然我們已經(jīng)得到了標(biāo)簽的內(nèi)容,那么問(wèn)題來(lái)了,我們要想獲取標(biāo)簽內(nèi)部的文字怎么辦呢?很簡(jiǎn)單,用.string即可,例如
print soup.p.string
#The Dormouse's story
print type(soup.p.string)
<class 'bs4.element.NavigableString'>
3. BeautifulSoup
BeautifulSoup對(duì)象表示的是一個(gè)文檔的內(nèi)容。大部門(mén)時(shí)候,可以用它當(dāng)做Tag對(duì)象,是一個(gè)特殊的Tag,我們可以分別獲取它的類(lèi)型,名稱,以及屬性來(lái)感受一下。
print type(soup.name)
#<type 'unicode'>
print soup.name
#[document]
print soup.attrs #文檔本身的屬性為空
#{}
4. Comment
Comment對(duì)象是一個(gè)特殊類(lèi)型的NavigableString對(duì)象,其輸出的內(nèi)容不包括注釋符號(hào)。
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)容實(shí)際上是注釋,但是如果我們利用.string來(lái)輸出它的內(nèi)容時(shí),注釋符號(hào)已經(jīng)去掉了。
遍歷文檔樹(shù)
1.直接子節(jié)點(diǎn):.contents .children屬性
.contents
tag的.contents屬性可以將tag的子節(jié)點(diǎn)以列表的方式輸出。
print soup.head.contents
#[<title>The Dormouse's story</title>]
輸出方式為列表,我們可以用列表索引來(lái)獲取它的某一個(gè)元素
print soup.head.contents[0]
#<title>The Dormouse's story</title>
.children
它返回的不是一個(gè)list,不過(guò)我們可以通過(guò)遍歷獲取所有子節(jié)點(diǎn)。
我們打印輸出.children看一下,可以發(fā)現(xiàn)他是一個(gè)list生成器對(duì)象。
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é)點(diǎn):.descendants屬性
.contents和.children屬性僅包含tag的直接子節(jié)點(diǎn),.descendants屬性可以對(duì)所有tag的子孫節(jié)點(diǎn)進(jìn)行遞歸循環(huán),和.children類(lèi)似,我們也需要遍歷獲取其中的內(nèi)容。
for child in soup.descendants:
print child
3. 節(jié)點(diǎn)內(nèi)容:.string屬性
如果tag只有一個(gè)NavigableString類(lèi)型子節(jié)點(diǎn),那么這個(gè)tag可以使用.string得到子節(jié)點(diǎn)。如果一個(gè)tag僅有一個(gè)子節(jié)點(diǎn),那么這個(gè)tag也可以使用.string,輸出結(jié)果與當(dāng)前唯一子節(jié)點(diǎn)的.string結(jié)果相同。
通俗點(diǎn)講就是:如果一個(gè)標(biāo)簽里面沒(méi)有標(biāo)簽了,那么.string就會(huì)返回標(biāo)簽里面的內(nèi)容。如果標(biāo)簽里面只有唯一的一個(gè)標(biāo)簽了,那么.string也會(huì)返回最里面的內(nèi)容。例如:
print soup.head.string
#The Dormouse's story
print soup.title.string
#The Dormouse's story
搜索文檔樹(shù)
1. find_all(name, attrs, recursive, text, **kwargs)
1) name參數(shù)
name參數(shù)可以查找所有名字為name的tag,字符串對(duì)象會(huì)自動(dòng)忽略掉。
A.傳字符串
最簡(jiǎn)單的過(guò)濾器是字符串,在搜索方法中傳入一個(gè)字符串參數(shù),eautiful Soup會(huì)自動(dòng)查找與字符串完整匹配的內(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.傳正則表達(dá)式
如果傳入正則表達(dá)式作為參數(shù),Beautiful Soup會(huì)通過(guò)正則表達(dá)式的match()來(lái)匹配內(nèi)容。下面例子中找出所有以b開(kāi)頭的標(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會(huì)將與列表中任一元素匹配的內(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ù)
通過(guò)text參數(shù)可以搜索文檔中的字符串內(nèi)容,與name參數(shù)的可選值一樣,text參數(shù)接收參數(shù)值,正則表達(dá)式,列表
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 方法有異曲同工之妙的查找方法.
- 寫(xiě) CSS 時(shí),標(biāo)簽名不加任何修飾,類(lèi)名前加.,id名前加#
- 在這里我們也可以利用類(lèi)似的方法來(lái)篩選元素,用到的方法是
soup.select(),返回類(lèi)型是list
