Python3.x的BeautifulSoup解析html常用函數
1,初始化:
soup = BeautifulSoup(html) # html為html源代碼字符串,type(html) == str
2,用tag獲取相應代碼塊的剖析樹:
#當用tag作為搜索條件時,我們獲取的包含這個tag塊的剖析樹: #<tag><xxx>ooo</xxx></tag> #這里獲取head這個塊 head = soup.find('head') # or # head = soup.head # or # head = soup.contents[0].contents[0]
contents屬性是一個列表,里面保存了該剖析樹的直接兒子,如:
html = soup.contents[0] # <html> ... </html> head = html.contents[0] # <head> ... </head> body = html.contents[1] # <body> ... </body>
3,用contents[], parent, nextSibling, previousSibling尋找父子兄弟tag:
beautifulSoup提供了幾個簡單的方法直接獲取當前tag塊的父子兄弟。
假設我們已經獲得了body這個tag塊,我們想要尋找<html>, <head>, 第一個<p>, 第二個<p>這四個tag塊:
# body = soup.bodyhtml = body.parent # html是body的父親 head = body.previousSibling # head和body在同一層,是body的前一個兄弟 p1 = body.contents[0] # p1, p2都是body的兒子,我們用contents[0]取得p1 p2 = p1.nextSibling # p2與p1在同一層,是p1的后一個兄弟, 當然body.content[1]也可得到 print(p1.text) # u'This is paragraphone.' print(p2.text) # u'This is paragraphtwo.' # 注意:1,每個tag的text包括了它以及它子孫的text。2,所有text已經被自動轉 #為unicode,如果需要,可以自行轉碼encode(xxx)
4,用find, findParent, findNextSibling, findPreviousSibling尋找祖先或者子孫 tag:
find方法(我理解和findChild是一樣的),就是以當前節點為起始,遍歷整個子樹,找到后返回。
而這些方法的復數形式,會找到所有符合要求的tag,以list的方式放回。他們的對應關系是:find->findall, findParent->findParents, findNextSibling->findNextSiblings...,如:
print soup.findAll('p') # [<p id="firstpara" align="center">This is paragraph <b>one</b>.</p>, <p id="secondpara" align="blah">This is paragraph <b>two</b>.</p>]
5,find的幾種用法,其他的類比: find(name=None, attrs={}, recursive=True, text=None, **kwargs),文檔參考: https://www.crummy.com/software/BeautifulSoup/bs3/documentation.zh.html#The%20basic%20find%20method:%20findAll%28name,%20attrs,%20recursive,%20text,%20limit,%20**kwargs%29)
(1).搜索tag:
find(tagname) # 直接搜索名為tagname的tag 如:find('head') find(list) # 搜索在list中的tag,如: find(['head', 'body']) find(dict) # 搜索在dict中的tag,如:find({'head':True, 'body':True}) find(re.compile('')) # 搜索符合正則的tag, 如:find(re.compile('^p')) 搜索以p開頭的tag find(lambda) # 搜索函數返回結果為true的tag, 如:find(lambda name: if len(name) == 1) 搜索長度為1的tag find(True) # 搜索所有tag
(2),搜索屬性(attrs):
find(id='xxx') # 尋找id屬性為xxx的 find(attrs={id=re.compile('xxx'), algin='xxx'}) # 尋找id屬性符合正則且algin屬性為xxx的 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