Python爬蟲之BeautifulSoup
簡介
Beautiful Soup提供一些簡單的、python式的函數(shù)用來處理導(dǎo)航、搜索、修改分析樹等功能。它是一個工具箱,通過解析文檔為用戶提供需要抓取的數(shù)據(jù),因為簡單,所以不需要多少代碼就可以寫出一個完整的應(yīng)用程序。Beautiful Soup自動將輸入文檔轉(zhuǎn)換為Unicode編碼,輸出文檔轉(zhuǎn)換為utf-8編碼。你不需要考慮編碼方式,除非文檔沒有指定一個編碼方式,這時,Beautiful Soup就不能自動識別編碼方式了。然后,你僅僅需要說明一下原始編碼方式就可以了。
Beautiful Soup已成為和lxml、html6lib一樣出色的python解釋器,為用戶靈活地提供不同的解析策略或強勁的速度。
安裝
- pip install BeautifulSoup4
- 或
- easy_install BeautifulSoup4
創(chuàng)建BeautifulSoup對象
首先應(yīng)該導(dǎo)入BeautifulSoup類庫
- from bs4 import BeautifulSoup
下面開始創(chuàng)建對像,在開始之前為了方便演示,先創(chuàng)建一個html文本,如下:
- 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 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>
- """
創(chuàng)建對象:soup=BeautifulSoup(html,’lxml’),這里的lxml是解析的類庫,目前來說個人覺得***的解析器了,一直在用這個,安裝方法:
- pip install lxml
Tag
Tag就是html中的一個標(biāo)簽,用BeautifulSoup就能解析出來Tag的具體內(nèi)容,具體的格式為soup.name,其中name是html下的標(biāo)簽,具體實例如下:
- print soup.title # 輸出title標(biāo)簽下的內(nèi)容,包括此標(biāo)簽,這個將會輸出<title>The Dormouse's story</title>
- print soup.head
注意:
這里的格式只能獲取這些標(biāo)簽的***個,后面會講到獲取多個標(biāo)簽的方法。其中對于Tag有兩個重要的屬性name和attrs,分別表示名字和屬性,介紹如下:
- name:對于Tag,它的name就是其本身,如soup.p.name就是p
- attrs是一個字典類型的,對應(yīng)的是屬性-值,如print soup.p.attrs,輸出的就是{‘class’: [‘title’], ‘name’: ‘dromouse’},當(dāng)然你也可以得到具體的值,如print soup.p.attrs[‘class’],輸出的就是[title]是一個列表的類型,因為一個屬性可能對應(yīng)多個值,當(dāng)然你也可以通過get方法得到屬性的,如:print soup.p.get(‘class’)。還可以直接使用print soup.p[‘class’]
get
get方法用于得到標(biāo)簽下的屬性值,注意這是一個重要的方法,在許多場合都能用到,比如你要得到<img src=”#”>標(biāo)簽下的圖像url,那么就可以用soup.img.get(‘src’),具體解析如下:
- print soup.p.get("class") #得到***個p標(biāo)簽下的src屬性
string
得到標(biāo)簽下的文本內(nèi)容,只有在此標(biāo)簽下沒有子標(biāo)簽,或者只有一個子標(biāo)簽的情況下才能返回其中的內(nèi)容,否則返回的是None具體實例如下:
- print soup.p.string #在上面的一段文本中p標(biāo)簽沒有子標(biāo)簽,因此能夠正確返回文本的內(nèi)容
- print soup.html.string #這里得到的就是None,因為這里的html中有很多的子標(biāo)簽
get_text()
可以獲得一個標(biāo)簽中的所有文本內(nèi)容,包括子孫節(jié)點的內(nèi)容,這是最常用的方法
搜索文檔樹
find_all( name , attrs , recursive , text , **kwargs )
find_all是用于搜索節(jié)點中所有符合過濾條件的節(jié)點
1. name參數(shù):是Tag的名字,如p,div,title …..
soup.find_all("p") 查找所有的p標(biāo)簽,返回的是[<b>The Dormouse's story</b>],可以通過遍歷獲取每一個節(jié)點,如下:
- ps=soup.find_all("p")
- for p in ps:
- print p.get('class') #得到p標(biāo)簽下的class屬性
傳入正則表達式:soup.find_all(re.compile(r’^b’)查找以b開頭的所有標(biāo)簽,這里的body和b標(biāo)簽都會被查到
傳入類列表:如果傳入列表參數(shù),BeautifulSoup會將與列表中任一元素匹配的內(nèi)容返回.下面代碼找到文檔中所有<a>標(biāo)簽和<b>標(biāo)簽
- soup.find_all(["a", "b"])
2. KeyWords參數(shù),就是傳入屬性和對應(yīng)的屬性值,或者一些其他的表達式
- soup.find_all(id='link2'),這個將會搜索找到所有的id屬性為link2的標(biāo)簽。傳入正則表達式soup.find_all(href=re.compile("elsie")),這個將會查找所有href屬性滿足正則表達式的標(biāo)簽
- 傳入多個值:soup.find_all(id='link2',class_='title') ,這個將會查找到同時滿足這兩個屬性的標(biāo)簽,這里的class必須用class_傳入?yún)?shù),因為class是python中的關(guān)鍵詞
- 有些屬性不能通過以上方法直接搜索,比如html5中的data-*屬性,不過可以通過attrs參數(shù)指定一個字典參數(shù)來搜索包含特殊屬性的標(biāo)簽,如下:
- # [<div data-foo="value">foo!</div>]
- data_soup.find_all(attrs={"data-foo": "value"}) #注意這里的atts不僅能夠搜索特殊屬性,亦可以搜索普通屬性
- soup.find_all("p",attrs={'class':'title','id':'value'}) #相當(dāng)與soup.find_all('p',class_='title',id='value')
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" href="http://example.com/elsie" id="link1">Elsie</a>,
- # <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>]
5. recursive 參數(shù):調(diào)用tag的 find_all() 方法時,BeautifulSoup會檢索當(dāng)前tag的所有子孫節(jié)點,如果只想搜索tag的直接子節(jié)點,可以使用參數(shù) recursive=False
find( name , attrs , recursive , text , **kwargs )
它與 find_all() 方法唯一的區(qū)別是 find_all() 方法的返回結(jié)果是值包含一個元素的列表,而 find() 方法直接返回結(jié)果,就是直接返回***匹配到的元素,不是列表,不用遍歷,如soup.find("p").get("class")
通過標(biāo)簽名查找
- print soup.select('title')
- #[<title>The Dormouse's story</title>]
- print soup.select('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>]
通過類名查找
- print soup.select('.sister')
- #[<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>]
通過id名查找
- print soup.select('#link1')
- #[<a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a>]
組合查找
學(xué)過 css 的都知道 css 選擇器,如 p #link1 是查找 p 標(biāo)簽下的 id 屬性為 link1 的標(biāo)簽
- print soup.select('p #link1') #查找p標(biāo)簽中內(nèi)容為id屬性為link1的標(biāo)簽
- #[<a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a>]
- print soup.select("head > title") #直接查找子標(biāo)簽
- #[<title>The Dormouse's story</title>]
屬性查找
查找時還可以加入屬性元素,屬性需要用中括號括起來,注意屬性和標(biāo)簽屬于同一節(jié)點,所以中間不能加空格,否則會無法匹配到。
- print soup.select('a[class="sister"]')
- #[<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>]
- print soup.select('a[href="http://example.com/elsie"]')
- #[<a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a>]
同樣,屬性仍然可以與上述查找方式組合,不在同一節(jié)點的空格隔開,同一節(jié)點的不加空格,代碼如下:
- print soup.select('p a[href="http://example.com/elsie"]')
- #[<a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a>]
以上的 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()