BeautifulSoup基本步驟

 

http://blog.csdn.net/kikaylee/article/details/56841789css

 

’BeautifulSoup是Python的一個庫,最主要的功能就是從網頁爬取咱們須要的數據。BeautifulSoup將html解析爲對象進行處理,所有頁面轉變爲字典或者數組,相對於正則表達式的方式,能夠大大簡化處理過程。html

0x01 安裝

建議安裝BeautifulSoup 4版本 利用pip進行安裝:python

pip install beautifulsoup4
  • 1

BeautifulSoup默認支持Python的標準HTML解析庫,可是它也支持一些第三方的解析庫:正則表達式

序號 解析庫 使用方法 優點 劣勢
1 Python標準庫 BeautifulSoup(html,’html.parser’) Python內置標準庫;執行速度快 容錯能力較差
2 lxml HTML解析庫 BeautifulSoup(html,’lxml’) 速度快;容錯能力強 須要安裝,須要C語言庫
3 lxml XML解析庫 BeautifulSoup(html,[‘lxml’,’xml’]) 速度快;容錯能力強;支持XML格式 須要C語言庫
4 htm5lib解析庫 BeautifulSoup(html,’htm5llib’) 以瀏覽器方式解析,最好的容錯性 速度慢

0x02 建立對象

導入庫:數據庫

from bs4 import BeautifulSoup
  • 1

建立實例:數組

url='http://www.baidu.com' resp=urllib2.urlopen(url) html=resp.read()
  • 1
  • 2
  • 3

建立對象:瀏覽器

 bs=BeautifulSoup(html)
  • 1
  • 2

格式化輸出內容:app

print bs.prettify()
  • 1

0x03 對象種類

BeautifulSoup將複雜的html文檔轉換爲樹形結構,每個節點都是一個對象,這些對象能夠概括爲幾種:ui

(1)Taglua

Tag至關於html種的一個標籤:

#提取Tag print bs.title print type(bs.title)
  • 1
  • 2
  • 3

結果:

<title>百度一下,你就知道</title> <class 'bs4.element.Tag'>
  • 1
  • 2

對於Tag,有幾個重要的屬性:

name:每一個Tag對象的name就是標籤本省的名稱; 
attrs:每一個Tag對象的attrs就是一個字典,包含了標籤的所有屬性。

print bs.a.name print bs.a.attrs
  • 1
  • 2

輸出:

a
{u'href': u'/', u'id': u'result_logo', u'onmousedown': u"return c({'fm':'tab','tab':'logo'})"}
  • 1
  • 2

(2)NavigableString

Comment是一種特殊的NavigableString,對應的是註釋的內容,可是其輸出不包含註釋符。看這樣的一個例子:

#coding:utf-8 from bs4 import BeautifulSoup html=''' <a class="css" href="http://example.com/test" id="test"><!--test --></a> ''' bs=BeautifulSoup(html,"html.parser") print bs.a print bs.a.string
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

運行結果:

<a class="css" href="http://example.com/test" id="test"><!--def --></a>
  • 1

a標籤的內容是註釋,可是使用.string仍然輸出了。這種狀況下,咱們須要作下判斷:

#判斷是不是註釋 if type(bs.a.string)==element.Comment: print bs.a.string
  • 1
  • 2
  • 3

再看下面的例子:

<a class="css1" href="http://example.com/cdd" id="css">abc<!--def -->gh</a>
  • 1

內容是註釋和字符串混合,此時能夠用contents獲取所有對象:

for i in bs.a.contents: print i
  • 1
  • 2

若是須要忽略註釋內容的話,能夠利用get_text()或者.text:

print bs.a.get_text()
  • 1

若是想在BeautifulSoup以外使用 NavigableString 對象,須要調用unicode()方法,將該對象轉換成普通的Unicode字符串,不然就算BeautifulSoup已方法已經執行結束,該對象的輸出也會帶有對象的引用地址,這樣會浪費內存。

0x04 搜索文檔樹

重點介紹下find_all()方法:

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

(1)name參數

name參數能夠查找全部名字爲name的Tag,字符串對象自動忽略掉。

print bs.find_all('a')
  • 1

傳列表:

print bs.find_all(['a','b'])
  • 1

傳入正則表達式:

print bs.find_all(re.compile('^b'))
  • 1

全部以b開頭的標籤對象都會被找到。 
傳遞方法:

def has_class_but_not_id(tag): return tag.has_attr('class') and not tag.has_attr('id') print bs.find_all(has_class_but_not_id)
  • 1
  • 2
  • 3

(2)kwyowrds關鍵字

print bs.find_all(id='css') print bs.find_all(id=re.compile('^a'))
  • 1
  • 2

還能夠混合使用:

print bs.find_all(id='css',href=re.compile('^ex'))
  • 1

可使用class做爲過濾,可是class是Python中的關鍵字,可使用class_代替,或者採用字典的形式傳輸參數:

print bs.find_all(class_='css') print bs.find_all(attrs={'class':'css'})
  • 1
  • 2

(3)text參數

用來搜索文檔中的字符串內容,text參數也接收字符串、正則表達式、列表、True等參數。

print bs.find_all(text=re.compile('^abc'))
  • 1

(4)limit參數

限制返回對象的個數,與數據庫SQL查詢相似。

(5)recursive參數

調用tag的find_all()方法時,BeautifulSoup會檢索當前tag的全部子孫節點,若是隻想搜索tag的直接子節點,可使用參數 recursive=False。

0x05 CSS選擇器

能夠採用CSS的語法格式來篩選元素:

#標籤選擇器 print bs.select('a') #類名選擇器 print bs.select('.css') #id選擇器 print bs.select('#css') #屬性選擇器 print bs.select('a[class="css"]') #遍歷 for tag in bs.select('a'): print tag.get_text()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

對於喜歡用CSS語法的人來講,這種方式很是方便。若是你僅僅須要CSS選擇器的功能,那麼直接使用 lxml 也能夠,並且速度更快,支持更多的CSS選擇器語法,但Beautiful Soup整合了CSS選擇器的語法和自身方便使用API。

相關文章
相關標籤/搜索