Beautiful Soup
是一個可以從HTML或XML文件中提取數(shù)據(jù)的Python庫.它能夠通過你喜歡的轉(zhuǎn)換器實現(xiàn)慣用的文檔導(dǎo)航,查找,修改文檔的方式.Beautiful Soup會幫你節(jié)省數(shù)小時甚至數(shù)天的工作時間. 文檔地址:http://beautifulsoup.readthedocs.io/zh_CN/latest/ 安裝: apt-get install python-bs4
Beautiful Soup 4 通過PyPi發(fā)布,所以如果你無法使用系統(tǒng)包管理安裝,那么也可以通過 easy_install 或 pip 來安裝.包的名字是 beautifulsoup4 ,這個包兼容Python2和Python3.
$ easy_install beautifulsoup4
$ pip install beautifulsoup4
依賴的解析器安裝: 安裝解析器 Beautiful Soup支持Python標準庫中的HTML解析器,還支持一些第三方的解析器,其中一個是 lxml .根據(jù)操作系統(tǒng)不同,可以選擇下列方法來安裝lxml:
$ apt-get install Python-lxml
$ easy_install lxml
$ pip install lxml
另一個可供選擇的解析器是純Python實現(xiàn)的 html5lib , html5lib的解析方式與瀏覽器相同,可以選擇下列方法來安裝html5lib:
$ apt-get install Python-html5lib
$ easy_install html5lib
$ pip install html5lib 推薦使用lxml作為解析器,因為效率更高. 在Python2.7.3之前的版本和Python3中3.2.2之前的版本,必須安裝lxml或html5lib, 因為那些Python版本的標準庫中內(nèi)置的HTML解析方法不夠穩(wěn)定.
下面開始使用這個庫(這里之講解簡單的用法,具體看文檔)
1.創(chuàng)建 Beautiful Soup 對象 首先必須要導(dǎo)入 bs4 庫
<python>#coding:utf-8from bs4 import BeautifulSoupimport lxml</python>
實例化Beautifulsoup ,創(chuàng)建對象 一段html代碼(可以是抓取的也可以是寫入的),也可以從文件里面。
<python>html='''一段html代碼'''soup = BeautifulSoup(html)soup = BeautifulSoup(open('百度一下,你就知道.html'))</python>
修改一下:后面添加lxml,表示用lxml解析器 soup = BeautifulSoup(open(‘baidu.html’),”lxml”)
這里加載百度首頁文件: 可以嘗試輸出:
<python>print soup #普通輸出print soup.prettify() #格式化輸出</python>
格式化輸出結(jié)果:
<html></html>
四大對象種類
Beautiful Soup將復(fù)雜HTML文檔轉(zhuǎn)換成一個復(fù)雜的樹形結(jié)構(gòu),每個節(jié)點都是Python對象,所有對象可以歸納為4種: Tag , NavigableString , BeautifulSoup , Comment .
(1)Tag
Tag 是什么?通俗點講就是 HTML 中的一個個標簽,例如:
<title>The Dormouse's story</title><a class="sister" id="link1">Elsie</a>
上面的 title a 等等 HTML 標簽加上里面包括的內(nèi)容就是 Tag,下面我們來感受一下怎樣用 Beautiful Soup 來方便地獲取 Tags
下面每一段代碼中注釋部分即為運行結(jié)果
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"></a>print soup.p#<p class="title" name="dromouse"><b>The Dormouse's story</b></p>
我們可以利用 soup加標簽名輕松地獲取這些標簽的內(nèi)容,是不是感覺比正則表達式方便多了?不過有一點是,它查找的是在所有內(nèi)容中的第一個符合要求的標簽,如果要查詢所有的標簽,我們在后面進行介紹。 我們可以驗證一下這些對象的類型
print type(soup.a)#<class 'bs4.element.Tag'>
對于 Tag,它有兩個重要的屬性,是 name 和 attrs,下面我們分別來感受一下:
name
print soup.nameprint soup.head.name#[document]#head
soup 對象本身比較特殊,它的 name 即為 [document],對于其他內(nèi)部標簽,輸出的值便為標簽本身的名稱。
attrs
print soup.p.attrs#{'class': ['title'], 'name': 'dromouse'}
在這里,我們把 p 標簽的所有屬性打印輸出了出來,得到的類型是一個字典。
如果我們想要單獨獲取某個屬性,可以這樣,例如我們獲取它的 class 叫什么
print soup.p['class']#['title']
還可以這樣,利用get方法,傳入屬性的名稱,二者是等價的
print soup.p.get('class')#['title']
我們可以對這些屬性和內(nèi)容等等進行修改,例如
soup.p['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
既然我們已經(jīng)得到了標簽的內(nèi)容,那么問題來了,我們要想獲取標簽內(nèi)部的文字怎么辦呢?很簡單,用 .string 即可,例如
print soup.p.string#The Dormouse's story
這樣我們就輕松獲取到了標簽里面的內(nèi)容,想想如果用正則表達式要多麻煩。它的類型是一個 NavigableString,翻譯過來叫 可以遍歷的字符串,不過我們最好還是稱它英文名字吧。
print type(soup.p.string)#<class 'bs4.element.NavigableString'>
來檢查一下它的類型
print type(soup.p.string)#<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.aprint soup.a.stringprint type(soup.a.string)
運行結(jié)果如下
<a class="sister" id="link1"></a> Elsie <class 'bs4.element.Comment'>
a 標簽里的內(nèi)容實際上是注釋,但是如果我們利用 .string 來輸出它的內(nèi)容,我們發(fā)現(xiàn)它已經(jīng)把注釋符號去掉了,所以這可能會給我們帶來不必要的麻煩。
另外我們打印輸出下它的類型,發(fā)現(xiàn)它是一個 Comment 類型,所以,我們在使用前最好做一下判斷,判斷代碼如下
if type(soup.a.string)==bs4.element.Comment:print soup.a.string
上面的代碼中,我們首先判斷了它的類型,是否為 Comment 類型,然后再進行其他操作,如打印輸出。 6. 遍歷文檔樹 (1)直接子節(jié)點
要點:.contents .children 屬性
.contents
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>
我們怎樣獲得里面的內(nèi)容呢?很簡單,遍歷一下就好了,代碼及結(jié)果如下
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" id="link1"></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 屬性
.descendants
.contents 和 .children 屬性僅包含tag的直接子節(jié)點,.descendants 屬性可以對所有tag的子孫節(jié)點進行遞歸循環(huán),和 children類似,我們也需要遍歷獲取其中的內(nèi)容。
for child in soup.descendants:print child
運行結(jié)果如下,可以發(fā)現(xiàn),所有的節(jié)點都被打印出來了,先生最外層的 HTML標簽,其次從 head 標簽一個個剝離,以此類推。
<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"></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"></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"></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"></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é)果相同。
通俗點說就是:如果一個標簽里面沒有標簽了,那么 .string 就會返回標簽里面的內(nèi)容。如果標簽里面只有唯一的一個標簽了,那么 .string 也會返回最里面的內(nèi)容。例如
print soup.head.string#The Dormouse's storyprint soup.title.string#The Dormouse's story
如果tag包含了多個子節(jié)點,tag就無法確定,string 方法應(yīng)該調(diào)用哪個子節(jié)點的內(nèi)容, .string 的輸出結(jié)果是 None
print soup.html.string# None
(4)多個內(nèi)容
知識點: .strings .stripped_strings 屬性.strings
獲取多個內(nèi)容,不過需要遍歷獲取,比如下面的例子
for string in soup.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
輸出的字符串中可能包含了很多空格或空行,使用 .stripped_strings 可以去除多余空白內(nèi)容
for string in soup.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'...'
(5)父節(jié)點
知識點: .parent 屬性p = soup.pprint p.parent.name#bodycontent = soup.head.title.stringprint content.parent.name#title
(6)全部父節(jié)點
知識點:.parents 屬性
通過元素的 .parents 屬性可以遞歸得到元素的所有父輩節(jié)點,例如
content = soup.head.title.stringfor parent in content.parents: print parent.nametitleheadhtml[document]
(7)兄弟節(jié)點
知識點:.next_sibling .previous_sibling 屬性
兄弟節(jié)點可以理解為和本節(jié)點處在統(tǒng)一級的節(jié)點,.next_sibling 屬性獲取了該節(jié)點的下一個兄弟節(jié)點,.previous_sibling 則與之相反,如果節(jié)點不存在,則返回 None
注意:實際文檔中的tag的 .next_sibling 和 .previous_sibling 屬性通常是字符串或空白,因為空白或者換行也可以被視作一個節(jié)點,所以得到的結(jié)果可能是空白或者換行
print soup.p.next_sibling# 實際該處為空白print soup.p.prev_sibling#None 沒有前一個兄弟節(jié)點,返回 Noneprint soup.p.next_sibling.next_sibling#<p class="story">Once upon a time there were three little sisters; and their names were#<a class="sister" id="link1"></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>#下一個節(jié)點的下一個兄弟節(jié)點是我們可以看到的節(jié)點
(8)全部兄弟節(jié)點
知識點:.next_siblings .previous_siblings 屬性
通過 .next_siblings 和 .previous_siblings 屬性可以對當(dāng)前節(jié)點的兄弟節(jié)點迭代輸出
for sibling in soup.a.next_siblings: print(repr(sibling)) # u',\n' # <a class="sister" id="link2">Lacie</a> # u' and\n' # <a class="sister" id="link3">Tillie</a> # u'; and they lived at the bottom of a well.' # None
(9)前后節(jié)點
知識點:.next_element .previous_element 屬性
與 .next_sibling .previous_sibling 不同,它并不是針對于兄弟節(jié)點,而是在所有節(jié)點,不分層次
比如 head 節(jié)點為
<head><title>The Dormouse's story</title></head>
那么它的下一個節(jié)點便是 title,它是不分層次關(guān)系的
print soup.head.next_element#<title>The Dormouse's story</title>
(10)所有前后節(jié)點
知識點:.next_elements .previous_elements 屬性
通過 .next_elements 和 .previous_elements 的迭代器就可以向前或向后訪問文檔的解析內(nèi)容,就好像文檔正在被解析一樣
for element in last_a_tag.next_elements: print(repr(element))# u'Tillie'# u';\nand they lived at the bottom of a well.'# u'\n\n'# <p class="story">...</p># u'...'# u'\n'# None
7.搜索文檔樹 (1)find_all( name , attrs , recursive , text , kwargs )
find_all() 方法搜索當(dāng)前tag的所有tag子節(jié)點,并判斷是否符合過濾器的條件
1)name 參數(shù)
name 參數(shù)可以查找所有名字為 name 的tag,字符串對象會被自動忽略掉
A.傳字符串
最簡單的過濾器是字符串.在搜索方法中傳入一個字符串參數(shù),Beautiful Soup會查找與字符串完整匹配的內(nèi)容,下面的例子用于查找文檔中所有的 標簽 soup.find_all(‘b’) # [The Dormouse’s story]**
print soup.find_all('a')#[<a class="sister" id="link1"></a>, <a class="sister" id="link2">Lacie</a>, <a class="sister" id="link3">Tillie</a>]
B.傳正則表達式
如果傳入正則表達式作為參數(shù),Beautiful Soup會通過正則表達式的 match() 來匹配內(nèi)容.下面例子中找出所有以b開頭的標簽,這表示和標簽都應(yīng)該被找到
import refor tag in soup.find_all(re.compile("^b")): print(tag.name)# body# b
C.傳列表
如果傳入列表參數(shù),Beautiful Soup會將與列表中任一元素匹配的內(nèi)容返回.下面代碼找到文檔中所有標簽和標簽
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>]
D.傳 True
True 可以匹配任何值,下面代碼查找到所有的tag,但是不會返回字符串節(jié)點
for tag in soup.find_all(True): print(tag.name)# html# head# title# body# p# b# p# a# a
E.傳方法
如果沒有合適過濾器,那么還可以定義一個方法,方法只接受一個元素參數(shù) [4] ,如果這個方法返回 True 表示當(dāng)前元素匹配并且被找到,如果不是則反回 False
下面方法校驗了當(dāng)前元素,如果包含 class 屬性卻不包含 id 屬性,那么將返回 True:
def has_class_but_no_id(tag): return tag.has_attr('class') and not tag.has_attr('id')
將這個方法作為參數(shù)傳入 find_all() 方法,將得到所有
標簽:
soup.find_all(has_class_but_no_id)# [<p class="title"><b>The Dormouse's story</b></p>,# <p class="story">Once upon a time there were...</p>,# <p class="story">...</p>]
2)keyword 參數(shù)
注意:如果一個指定名字的參數(shù)不是搜索內(nèi)置的參數(shù)名,搜索時會把該參數(shù)當(dāng)作指定名字tag的屬性來搜索,如果包含一個名字為 id 的參數(shù),Beautiful Soup會搜索每個tag的”id”屬性soup.find_all(id='link2')# [<a class="sister" id="link2">Lacie</a>]
如果傳入 href 參數(shù),Beautiful Soup會搜索每個tag的”href”屬性
soup.find_all(href=re.compile("elsie"))# [<a class="sister" id="link1">Elsie</a>]
使用多個指定名字的參數(shù)可以同時過濾tag的多個屬性
soup.find_all(href=re.compile("elsie"), id='link1')# [<a class="sister" id="link1">three</a>]
在這里我們想用 class 過濾,不過 class 是 python 的關(guān)鍵詞,這怎么辦?加個下劃線就可以
soup.find_all("a", class_="sister")# [<a class="sister" id="link1">Elsie</a>,# <a class="sister" id="link2">Lacie</a>,# <a class="sister" id="link3">Tillie</a>]
有些tag屬性在搜索不能使用,比如HTML5中的 data-* 屬性
soup.find_all("a", class_="sister")# [<a class="sister" id="link1">Elsie</a>,# <a class="sister" id="link2">Lacie</a>,# <a class="sister" id="link3">Tillie</a>]
但是可以通過 find_all() 方法的 attrs 參數(shù)定義一個字典參數(shù)來搜索包含特殊屬性的tag
data_soup.find_all(attrs={"data-foo": "value"})# [<div data-foo="value">foo!</div>]
3)text 參數(shù)
通過 text 參數(shù)可以搜搜文檔中的字符串內(nèi)容.與 name 參數(shù)的可選值一樣, text 參數(shù)接受 字符串 , 正則表達式 , 列表, True
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"]
4)limit 參數(shù)
find_all() 方法返回全部的搜索結(jié)構(gòu),如果文檔樹很大那么搜索會很慢.如果我們不需要全部結(jié)果,可以使用 limit 參數(shù)限制返回結(jié)果的數(shù)量.效果與SQL中的limit關(guān)鍵字類似,當(dāng)搜索到的結(jié)果數(shù)量達到 limit 的限制時,就停止搜索返回結(jié)果.
文檔樹中有3個tag符合搜索條件,但結(jié)果只返回了2個,因為我們限制了返回數(shù)量
soup.find_all("a", limit=2)# [<a class="sister" id="link1">Elsie</a>,# <a class="sister" id="link2">Lacie</a>]
5)recursive 參數(shù)
調(diào)用tag的 find_all() 方法時,Beautiful Soup會檢索當(dāng)前tag的所有子孫節(jié)點,如果只想搜索tag的直接子節(jié)點,可以使用參數(shù) recursive=False .
一段簡單的文檔:
復(fù)制代碼 代碼如下:
<html> <head> <title> The Dormouse's story </title> </head> ...
是否使用 recursive 參數(shù)的搜索結(jié)果:
soup.html.find_all("title")# [<title>The Dormouse's story</title>]soup.html.find_all("title", recursive=False)# []
(2)find( name , attrs , recursive , text , **kwargs )
它與 find_all() 方法唯一的區(qū)別是 find_all() 方法的返回結(jié)果是值包含一個元素的列表,而 find() 方法直接返回結(jié)果 (3)find_parents() find_parent()
find_all() 和 find() 只搜索當(dāng)前節(jié)點的所有子節(jié)點,孫子節(jié)點等. find_parents() 和 find_parent() 用來搜索當(dāng)前節(jié)點的父輩節(jié)點,搜索方法與普通tag的搜索方法相同,搜索文檔搜索文檔包含的內(nèi)容 (4)find_next_siblings() find_next_sibling()
這2個方法通過 .next_siblings 屬性對當(dāng) tag 的所有后面解析的兄弟 tag 節(jié)點進行迭代, find_next_siblings() 方法返回所有符合條件的后面的兄弟節(jié)點,find_next_sibling() 只返回符合條件的后面的第一個tag節(jié)點 (5)find_previous_siblings() find_previous_sibling()
這2個方法通過 .previous_siblings 屬性對當(dāng)前 tag 的前面解析的兄弟 tag 節(jié)點進行迭代, find_previous_siblings() 方法返回所有符合條件的前面的兄弟節(jié)點, find_previous_sibling() 方法返回第一個符合條件的前面的兄弟節(jié)點 (6)find_all_next() find_next()
這2個方法通過 .next_elements 屬性對當(dāng)前 tag 的之后的 tag 和字符串進行迭代, find_all_next() 方法返回所有符合條件的節(jié)點, find_next() 方法返回第一個符合條件的節(jié)點 (7)find_all_previous() 和 find_previous()
這2個方法通過 .previous_elements 屬性對當(dāng)前節(jié)點前面的 tag 和字符串進行迭代, find_all_previous() 方法返回所有符合條件的節(jié)點, find_previous()方法返回第一個符合條件的節(jié)點
注:以上(2)(3)(4)(5)(6)(7)方法參數(shù)用法與 find_all() 完全相同,原理均類似,在此不再贅述。
8.CSS選擇器
我們在寫 CSS 時,標簽名不加任何修飾,類名前加點,id名前加 #,在這里我們也可以利用類似的方法來篩選元素,用到的方法是 soup.select(),返回類型是 list (1)通過標簽名查找
print soup.select('title') #[<title>The Dormouse's story</title>]print soup.select('a')#[<a class="sister" id="link1"></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"></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"></a>]
(4)組合查找
組合查找即和寫 class 文件時,標簽名與類名、id名進行的組合原理是一樣的,例如查找 p 標簽中,id 等于 link1的內(nèi)容,二者需要用空格分開
print soup.select('p #link1')#[<a class="sister" id="link1"></a>]
直接子標簽查找
print soup.select("head > title")#[<title>The Dormouse's story</title>]
(5)屬性查找
查找時還可以加入屬性元素,屬性需要用中括號括起來,注意屬性和標簽屬于同一節(jié)點,所以中間不能加空格,否則會無法匹配到。
print soup.select("head > title")#[<title>The Dormouse's story</title>]print soup.select('a[href="http://example.com/elsie"]')#[<a class="sister" id="link1"></a>]
同樣,屬性仍然可以與上述查找方式組合,不在同一節(jié)點的空格隔開,同一節(jié)點的不加空格
print soup.select('p a[href="http://example.com/elsie"]')#[<a class="sister" id="link1"></a>]
好,這就是另一種與 find_all 方法有異曲同工之妙的查找方法