Python中Beautifulsoup學習筆記二

1、用tag獲取相應代碼塊的剖析樹:

contents屬性是一個列表,裏面保存了該剖析樹的直接兒子。

如:
1 html = soup.contents[0] # <html> ... </html>
2 head = html.contents[0] # <head> ... </head>
3 body = html.contents[1] # <body> ... </body>

2、用contents[], parent, nextSibling, previousSibling尋找父子兄弟tag

爲了更加方便靈活的分析html代碼塊,beautifulSoup提供了幾個簡單的方法直接獲取當前tag塊的父子兄弟。

假設我們已經獲得了body這個tag塊,我們想要尋找<html>, <head>, 第一個<p>, 第二個<p>這四個tag塊:

 

3、用find, findParent, findNextSibling, findPreviousSibling尋找祖先或者子孫 tag:

有了上面的基礎,這裏應該很好理解了,例如find方法(我理解和findChild是一樣的),就是以當前節點爲起始,遍歷整個子樹,找到後返回。

  而這些方法的複數形式,會找到所有符合要求的tag,以list的方式放回。他們的對應關係是:find->findall, findParent->findParents, findNextSibling->findNextSiblings...

 

裏我們重點講一下find的幾種用法,其他的類比:

  find(name=None, attrs={}, recursive=True, text=None, **kwargs)

(ps:只講幾種用法,完整請看官方link :http://www.crummy.com/software/BeautifulSoup/bs3/documentation.zh.html#The%20basic%20find%20method:%20findAll%28name,%20attrs,%20recursive,%20text,%20limit,%20**kwargs%29

  1) 搜索tag:

1 find(tagname)        # 直接搜索名爲tagname的tag 如:find('head')
2 find(list)           # 搜索在list中的tag,如: find(['head', 'body'])
3 find(dict)           # 搜索在dict中的tag,如:find({'head':True, 'body':True})
4 find(re.compile('')) # 搜索符合正則的tag, 如:find(re.compile('^p')) 搜索以p開頭的tag
5 find(lambda)         # 搜索函數返回結果爲true的tag, 如:find(lambda name: if len(name) == 1) 搜索長度爲1的tag
6 find(True)           # 搜索所有tag

 2) 搜索屬性(attrs):

1 find(id='xxx')                                  # 尋找id屬性爲xxx的
2 find(attrs={id=re.compile('xxx'), algin='xxx'}) # 尋找id屬性符合正則且algin屬性爲xxx的
3 find(attrs={id=True, algin=None})               # 尋找有id屬性但是沒有algin屬性的

3) 搜索文字(text):

注意,文字的搜索會導致其他搜索給的值如:tag, attrs都失效。

方法與搜索tag一致

4) recursive, limit:

recursive=False表示只搜索直接兒子,否則搜索整個子樹,默認爲True。

當使用findAll或者類似返回list的方法時,limit屬性用於限制返回的數量,如findAll('p', limit=2): 返回首先找到的兩個tag

 

參考鏈接:http://www.cnblogs.com/twinsclover/archive/2012/04/26/2471704.html

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章