BeautifulSoup是Python的一個第三方庫,可用于幫助解析html/XML等內容,以抓取特定的網頁信息。目前最新的是v4版本,這里主要總結一下我使用的v3版本解析html的一些常用方法。
準備
1.Beautiful Soup安裝
為了能夠對頁面中的內容進行解析,本文使用Beautiful Soup。當然,本文的例子需求較簡單,完全可以使用分析字符串的方式。
執行
sudo easy_install beautifulsoup4
即可安裝。
2.requests模塊的安裝
requests模塊用于加載要請求的web頁面。
在python的命令行中輸入import requests,報錯說明requests模塊沒有安裝。
我這里打算采用easy_install的在線安裝方式安裝,發現系統中并不存在easy_install命令,輸入sudo apt-get install python-setuptools來安裝easy_install工具。
執行sudo easy_install requests安裝requests模塊。
基礎
1.初始化
導入模塊
#!/usr/bin/env pythonfrom BeautifulSoup import BeautifulSoup #process html#from BeautifulSoup import BeautifulStoneSoup #process xml#import BeautifulSoup #all
創建對象:str初始化,常用urllib2或browser返回的html初始化BeautifulSoup對象。
doc = ['hello', 'This is paragraph one of ptyhonclub.org.', 'This is paragraph two of pythonclub.org.', '']soup = BeautifulSoup(''.join(doc))
指定編碼:當html為其他類型編碼(非utf-8和asc ii),比如GB2312的話,則需要指定相應的字符編碼,BeautifulSoup才能正確解析。
htmlCharset = "GB2312"soup = BeautifulSoup(respHtml, fromEncoding=htmlCharset)
2.獲取tag內容
尋找感興趣的tag塊內容,返回對應tag塊的剖析樹
head = soup.find('head')#head = soup.head#head = soup.contents[0].contents[0]print head
返回內容:hello
說明一下,contents屬性是一個列表,里面保存了該剖析樹的直接兒子。
html = soup.contents[0] # <html> ... </html>head = html.contents[0] # <head> ... </head>body = html.contents[1] # <body> ... </body>
3.獲取關系節點
使用parent獲取父節點
body = soup.bodyhtml = body.parent # html是body的父親
使用nextSibling, previousSibling獲取前后兄弟
head = body.previousSibling # head和body在同一層,是body的前一個兄弟p1 = body.contents[0] # p1, p2都是body的兒子,我們用contents[0]取得p1p2 = p1.nextSibling # p2與p1在同一層,是p1的后一個兄弟, 當然body.content[1]也可得到
contents[]的靈活運用也可以尋找關系節點,尋找祖先或者子孫可以采用findParent(s), findNextSibling(s), findPreviousSibling(s)
4.find/findAll用法詳解
函數原型:find(name=None, attrs={}, recursive=True, text=None, **kwargs),findAll會返回所有符合要求的結果,并以list返回。
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開頭的tagfind(lambda) # 搜索函數返回結果為true的tag, 如:find(lambda name: if len(name) == 1) 搜索長度為1的tagfind(True) # 搜索所有tag
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屬性的resp1 = soup.findAll('a', attrs = {'href': match1})resp2 = soup.findAll('h1', attrs = {'class': match2})resp3 = soup.findAll('img', attrs = {'id': match3})
text搜索
文字的搜索會導致其他搜索給的值如:tag, attrs都失效。方法與搜索tag一致
print p1.text# u'This is paragraphone.'print p2.text# u'This is paragraphtwo.'# 注意:1,每個tag的text包括了它以及它子孫的text。2,所有text已經被自動轉為unicode,如果需要,可以自行轉碼encode(xxx)
recursive和limit屬性
recursive=False表示只搜索直接兒子,否則搜索整個子樹,默認為True。當使用findAll或者類似返回list的方法時,limit屬性用于限制返回的數量,如findAll('p', limit=2): 返回首先找到的兩個tag。
實例
本文以博客的文檔列表頁面為例,利用python對頁面中的文章名進行提取。
文章列表頁中的文章列表部分的url如下:
<ul class="listing"> <li class="listing-item"><span class="date">2014-12-03</span><a href="/post/linux_funtion_advance_feature" </li> <li class="listing-item"><span class="date">2014-12-02</span><a href="/post/cgdb" </li>...</ul>
代碼:
#!/usr/bin/env python # -*- coding: utf-8 -*-' a http parse test programe '__author__ = 'kuring lv'import requestsimport bs4archives_url = "http://kuring.me/archive"def start_parse(url) : print "開始獲取(%s)內容" % url response = requests.get(url) print "獲取網頁內容完畢" soup = bs4.BeautifulSoup(response.content.decode("utf-8")) #soup = bs4.BeautifulSoup(response.text); # 為了防止漏掉調用close方法,這里使用了with語句 # 寫入到文件中的編碼為utf-8 with open('archives.txt', 'w') as f : for archive in soup.select("li.listing-item a") : f.write(archive.get_text().encode('utf-8') + "/n") print archive.get_text().encode('utf-8')# 當命令行運行該模塊時,__name__等于'__main__'# 其他模塊導入該模塊時,__name__等于'parse_html'if __name__ == '__main__' : start_parse(archives_url)