標籤:ocs dom amp png post 支援 img 結果 import
CSS選取器:BeautifulSoup4
和lxml一樣,Beautiful Soup也是一個HTML/XML的解析器,主要的功能也是如何解析和提取HTML/XML資料。
lxml只會局部遍曆,而Beautiful Soup是基於HTML DOM的,會載入整個文檔,解析整個DOM樹,因此時間和記憶體開銷都會大很多,所以效能要低於lxml。
BeautifulSoup用來解析HTML比較簡單,API非常人性化,支援CSS選取器、Python標準庫中的HTML解析器,也支援lxml的XML解析器。
Beautiful Soup3目前已經停止開發,推薦現在的項目使用Beautiful Soup。使用pip安裝即可:pip install beautifulsoup4
官方文檔: http://beautifulsoup.readthedocs.io/zh_CN/v4.4.0
|抓取工具|速度|使用難道|安裝難度|
|---|---|--|----|
|正則|最快|困難|無(內建)|
|BeautifulSoup|慢|最簡單|簡單|
|lxml|快|簡單|一般|
執行個體:
首先必須要匯入bs4庫
# 07-urllib2_beautipulsoup_prettifyfrom bs4 import BeautifulSouphtml = """<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 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>"""#建立 Beautiful Soup 對象soup = BeautifulSoup(html)#開啟本地 HTML 檔案的方式來建立對象#soup = BeautifulSoup(open('index.html'))#格式化輸出 soup 對象的內容print soup.prettify()
運行結果:
<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" href="http://example.com/elsie" id="link1"> <!-- Elsie --> </a> , <a class="sister" href="http://example.com/lacie" id="link2"> Lacie </a> and <a class="sister" href="http://example.com/tillie" id="link3"> Tillie </a> ;and they lived at the bottom of a well. </p> <p class="story"> ... </p> </body></html>
- 如果我們在IPython2下執行,會看到這樣一段警告:
- 意思是,如果我們沒有顯示地指定解析器,所以預設使用這個系統的最佳可用HTML解析器("lxml")。如果你在另一個系統中運行這段代碼,或者在不同的虛擬環境中,使用不同的解析器造成行為不同。
- 但是我們可以通過
soup = BeautifulSoup(html, "lxml")
四大對象種類
Beautiful Soup將複雜HTML文檔轉換成一個複雜的樹形結構,每個節點都是Python對象,所有對象可以歸納為4種:
- Tag
- NaviganleString
- BeautifulSoup
- Comment
1.Tag
Tag通俗點講就是HTM中的一個個標籤,例如:
<head><title>The Dormouse's story</title></head><a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a><p class="title" name="dromouse"><b>The Dormouse's story</b></p>
上面的title、head、a、p等等標籤上加上裡麵包括的內容就是Tag,那麼試著使用Beautiful Soup來擷取Tags
#-*- coding:utf-8 -*-#08-urllib2_beautifulsoup_tag.pyfrom bs4 import BeautifulSouphtml = """<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 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>"""#建立Beautiful Soup對象soup = BeautifulSoup(html)print soup.title#<title>The Dormouse's story</title>print soup.a#<a class="sister" href="http://example.com/elsie" 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 加標籤名輕鬆地擷取這些標籤的內容,這些對象的類型是bs4.element.Tag。但是注意,它尋找的是在所有內容中的第一個符合要求的標籤。如果要查詢所有的標籤,後面會進行介紹。
對於Tag,它有兩個重要的屬性,是name和attrs
print soup.name#[document] #soup對象本身比較特殊,它的name即為[document]print soup.head.name#head #對於其他內部標籤,輸出的值便為標籤本身的名稱print soup.p.attrs#{'class':['title'], 'name':'dromouse'}#在這裡,我們把p標籤的所有屬性列印出來,得到的類型是一個字典print soup.p['class'] #soup.p.get('class')#['title'] #還可以利用get方法,傳入屬性的方法,二者是等價的。 soup.a['class'] = 'newClass'print soup.p #可以對這些屬性和內容等等進行修改# <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
既然我們已經得到了標籤的內容,那麼問題來了,我們要想擷取標籤內部的文字怎麼辦呢?很簡單,用.string即可,例如
print soup.p.string#The Dormouse's storyprint type(soup.p.string) <class 'bs4.element.NavigableString'>
3. BeautifulSoup
BeautifulSoup對象表示的是一個文檔的內容。大部門時候,可以用它當做Tag對象,是一個特殊的Tag,我們可以分別擷取它的類型,名稱,以及屬性來感受一下。
print type(soup.name)#<type 'unicode'>print soup.name#[document]print soup.attrs #文檔本身的屬性為空白#{}
4. Comment
Comment對象時一個特殊類型的NavigableString對象,其輸出的內容不包括注釋符號。
print soup.a# <a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a>print soup.a.string#Elsieprint type(soup.a.string)# <class 'bs4.element.Comment'>
a標籤裡的內容實際上是注釋,但是如果我們利用.string來輸出它的內容時,注釋符號已經去掉了。
遍曆文檔樹1.直接子節點:
.contents
.children屬性
.content
tag的.content屬性可以將tag的子節點以列表的方式輸出。
print soup.head.contents#[<title>The Dormouse's story</title>]
輸出方式為列表,我們可以用清單索引來擷取它的某一個元素
print soup.head.contents[0]#<title>The Dormouse's story</title>
.children
它返回的不是一個list,不過我們可以通過遍曆擷取所有子節點。
我們列印輸出.children看一下,可以發現他是一個list產生器對象。
print soup.head.children#<listiterator object at 0x7f71457f5710>for child in soup.body.children: print child
結果:
<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" href="http://example.com/elsie" id="link1"><!-- Elsie --></a>,<a class="sister" href="http://example.com/lacie" id="link2">Lacie</a> and<a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>;and they lived at the bottom of a well.</p><p class="story">...</p>
2. 所有子孫節點:
.descendants屬性
.contents和.children屬性僅包含tag的直接子節點,.descendants屬性可以對所有tag的子孫節點進行遞迴迴圈,和.children類似,我們也需要遍曆擷取其中的內容。
for child in soup.descendants: print child
3. 節點內容:
.string屬性
如果tag只有一個NavigableString類型子節點,那麼這個tag可以使用.string得到子節點。如果一個tag僅有一個子節點,那麼這個tag也可以使用.string,輸出結果與當前唯一子節點的.string結果相同。
通俗點講就是:如果一個標籤裡面沒有標籤了,那麼.string就會返回標籤裡面的內容。如果標籤裡面只有唯一的一個標籤了,那麼.string也會返回最裡面的內容。例如:
print soup.head.string#The Dormouse's storyprint soup.title.string#The Dormouse's story
搜尋文檔樹1. find_all(name, attrs, recursive, text, **kwargs)1) name參數
name參數可以尋找所有民資為name的tag,字串對象會自動忽略掉。
A.傳字串
最簡單的過濾器是字串,在搜尋方法中傳入一個字串參數,eautiful Soup會自動尋找與字串完整匹配的內容,下面的例子用於尋找文檔中所有的標籤:
soup.find_all('b')#[<b>The Dormouse's story</b>]print soup.find_all('a')#[<a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a>, <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>, <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]
B.傳Regex
如果傳入Regex作為參數,Beautiful Soup會通過Regex的match()來匹配內容。下面例子中找出所有以b開頭的標籤,這表示<body>和<b>標籤都應該被找到。
import refor tag in soup.find_all(re.compile('^b')): print(tag.name)#body#b
C.傳列表
如果傳入列表參數,Beautiful Soup會將與列表中任一元素匹配的內容返回 下面代碼找到文檔中所有<a>標籤和<b>標籤:
soup.find_all(['a', 'b'])# [<b>The Dormouse's story</b>,# <a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>,# <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>,# <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]
2) keyword參數soup.find_all(id='link2')# [<a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>]
3) text參數通過text參數可以搜尋文檔中的字串內容,與name參數的可選值一樣,text參數接收參數值,Regex,列表
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 時,標籤名不加任何修飾,類名前加.,id名前加#
- 在這裡我們也可以利用類似的方法來篩選元素,用到的方法是
soup.select(),傳回型別是 list
Python爬蟲(十四)_BeautifulSoup4 解析器