Python 爬蟲之 BeautifulSoup

簡介css

 

Beautiful Soup提供一些簡單的、python式的函數用來處理導航、搜索、修改分析樹等功能。它是一個工具箱,經過解析文檔爲用戶提供須要抓取的數據,由於簡單,因此不須要多少代碼就能夠寫出一個完整的應用程序。Beautiful Soup自動將輸入文檔轉換爲Unicode編碼,輸出文檔轉換爲utf-8編碼。你不須要考慮編碼方式,除非文檔沒有指定一個編碼方式,這時,Beautiful Soup就不能自動識別編碼方式了。而後,你僅僅須要說明一下原始編碼方式就能夠了。html

 

Beautiful Soup已成爲和lxml、html6lib同樣出色的python解釋器,爲用戶靈活地提供不一樣的解析策略或強勁的速度。html5

 

安裝python

 

pip install BeautifulSoup4正則表達式

函數

easy_install BeautifulSoup4工具

 

建立BeautifulSoup對象編碼

 

首先應該導入BeautifulSoup類庫 url

 

from bs4 import BeautifulSoupspa

 

下面開始建立對像,在開始以前爲了方便演示,先建立一個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>

"""

 

建立對象:soup=BeautifulSoup(html,’lxml’),這裏的lxml是解析的類庫,目前來講我的以爲最好的解析器了,一直在用這個,安裝方法:

 

pip install lxml

 

Tag

 

Tag就是html中的一個標籤,用BeautifulSoup就能解析出來Tag的具體內容,具體的格式爲soup.name,其中name是html下的標籤,具體實例以下:

 

print soup.title  # 輸出title標籤下的內容,包括此標籤,這個將會輸出<title>The Dormouse's story</title>

print soup.head

 

注意:

 

這裏的格式只能獲取這些標籤的第一個,後面會講到獲取多個標籤的方法。其中對於Tag有兩個重要的屬性name和attrs,分別表示名字和屬性,介紹以下:

 

  • name:對於Tag,它的name就是其自己,如soup.p.name就是p

  • attrs是一個字典類型的,對應的是屬性-值,如print soup.p.attrs,輸出的就是{‘class’: [‘title’], ‘name’: ‘dromouse’},固然你也能夠獲得具體的值,如print soup.p.attrs[‘class’],輸出的就是[title]是一個列表的類型,由於一個屬性可能對應多個值,固然你也能夠經過get方法獲得屬性的,如:print soup.p.get(‘class’)。還能夠直接使用print soup.p[‘class’]

 

get

 

get方法用於獲得標籤下的屬性值,注意這是一個重要的方法,在許多場合都能用到,好比你要獲得<img src=」#」>標籤下的圖像url,那麼就能夠用soup.img.get(‘src’),具體解析以下:

 

print soup.p.get("class") #獲得第一個p標籤下的src屬性

 

string

 

獲得標籤下的文本內容,只有在此標籤下沒有子標籤,或者只有一個子標籤的狀況下才能返回其中的內容,不然返回的是None具體實例以下:

 

print soup.p.string #在上面的一段文本中p標籤沒有子標籤,所以可以正確返回文本的內容

    

print soup.html.string  #這裏獲得的就是None,由於這裏的html中有不少的子標籤

 

get_text()

 

能夠得到一個標籤中的全部文本內容,包括子孫節點的內容,這是最經常使用的方法

 

搜索文檔樹

 

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

 

find_all是用於搜索節點中全部符合過濾條件的節點

 

1. name參數:是Tag的名字,如p,div,title …..

 

soup.find_all("p") 查找全部的p標籤,返回的是[<b>The Dormouse's story</b>],能夠經過遍歷獲取每個節點,以下:

 

ps=soup.find_all("p")

for p in ps:

    print p.get('class')   #獲得p標籤下的class屬性

 

傳入正則表達式:soup.find_all(re.compile(r’^b’)查找以b開頭的全部標籤,這裏的body和b標籤都會被查到

 

傳入類列表:若是傳入列表參數,BeautifulSoup會將與列表中任一元素匹配的內容返回.下面代碼找到文檔中全部<a>標籤和<b>標籤

 

soup.find_all(["a", "b"])

 

2. KeyWords參數,就是傳入屬性和對應的屬性值,或者一些其餘的表達式

 

  • soup.find_all(id='link2'),這個將會搜索找到全部的id屬性爲link2的標籤。傳入正則表達式soup.find_all(href=re.compile("elsie")),這個將會查找全部href屬性知足正則表達式的標籤

  • 傳入多個值:soup.find_all(id='link2',class_='title') ,這個將會查找到同時知足這兩個屬性的標籤,這裏的class必須用class_傳入參數,由於class是python中的關鍵詞

  • 有些屬性不能經過以上方法直接搜索,好比html5中的data-*屬性,不過能夠經過attrs參數指定一個字典參數來搜索包含特殊屬性的標籤,以下:

 

# [<div data-foo="value">foo!</div>]

data_soup.find_all(attrs={"data-foo""value"})   #注意這裏的atts不只可以搜索特殊屬性,亦能夠搜索普通屬性

 

soup.find_all("p",attrs={'class':'title','id':'value'})  #至關與soup.find_all('p',class_='title',id='value')

 

3. text參數:經過 text 參數能夠搜搜文檔中的字符串內容.與 name 參數的可選值同樣, text 參數接受 字符串 , 正則表達式 , 列表, 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參數:find_all() 方法返回所有的搜索結構,若是文檔樹很大那麼搜索會很慢.若是咱們不須要所有結果,可使用 limit 參數限制返回結果的數量.效果與SQL中的limit關鍵字相似,當搜索到的結果數量達到 limit 的限制時,就中止搜索返回結果.

 

文檔樹中有3個tag符合搜索條件,但結果只返回了2個,由於咱們限制了返回數量,代碼以下:

 

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 參數:調用tag的 find_all() 方法時,BeautifulSoup會檢索當前tag的全部子孫節點,若是隻想搜索tag的直接子節點,可使用參數 recursive=False

 

find( name , attrs , recursive , text , **kwargs )

 

它與 find_all() 方法惟一的區別是 find_all() 方法的返回結果是值包含一個元素的列表,而 find() 方法直接返回結果,就是直接返回第一匹配到的元素,不是列表,不用遍歷,如soup.find("p").get("class")

 

經過標籤名查找

 

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

 

組合查找

 

學過 css 的都知道 css 選擇器,如 p #link1 是查找 p 標籤下的 id 屬性爲 link1 的標籤

 

print soup.select('p #link1')    #查找p標籤中內容爲id屬性爲link1的標籤

#[<a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a>]

 

print soup.select("head > title")   #直接查找子標籤

#[<title>The Dormouse's story</title>]

 

屬性查找

 

查找時還能夠加入屬性元素,屬性須要用中括號括起來,注意屬性和標籤屬於同一節點,因此中間不能加空格,不然會沒法匹配到。

 

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

 

一樣,屬性仍然能夠與上述查找方式組合,不在同一節點的空格隔開,同一節點的不加空格,代碼以下:

 

print soup.select('p a[href="http://example.com/elsie"]')

#[<a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a>]

 

以上的 select 方法返回的結果都是列表形式,能夠遍歷形式輸出,而後用 get_text() 方法來獲取它的內容

 

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

相關文章
相關標籤/搜索