Python使用BeautifulSoup庫解析HTML基本使用教程
BeautifulSoup是Python的一個第三方庫,可用于幫助解析html/XML等內(nèi)容,以抓取特定的網(wǎng)頁信息。目前最新的是v4版本,這里主要總結(jié)一下我使用的v3版本解析html的一些常用方法。
準(zhǔn)備
1.Beautiful Soup安裝
為了能夠?qū)撁嬷械膬?nèi)容進行解析,本文使用Beautiful Soup。當(dāng)然,本文的例子需求較簡單,完全可以使用分析字符串的方式。
執(zhí)行
sudo easy_install beautifulsoup4
即可安裝。
2.requests模塊的安裝
requests模塊用于加載要請求的web頁面。
在python的命令行中輸入import requests,報錯說明requests模塊沒有安裝。
我這里打算采用easy_install的在線安裝方式安裝,發(fā)現(xiàn)系統(tǒng)中并不存在easy_install命令,輸入sudo apt-get install python-setuptools來安裝easy_install工具。
執(zhí)行sudo easy_install requests安裝requests模塊。
基礎(chǔ)
1.初始化
導(dǎo)入模塊
#!/usr/bin/env python from BeautifulSoup import BeautifulSoup #process html #from BeautifulSoup import BeautifulStoneSoup #process xml #import BeautifulSoup #all
創(chuàng)建對象: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))
指定編碼:當(dāng)html為其他類型編碼(非utf-8和asc ii),比如GB2312的話,則需要指定相應(yīng)的字符編碼,BeautifulSoup才能正確解析。
htmlCharset = "GB2312" soup = BeautifulSoup(respHtml, fromEncoding=htmlCharset)
2.獲取tag內(nèi)容
尋找感興趣的tag塊內(nèi)容,返回對應(yīng)tag塊的剖析樹
head = soup.find('head') #head = soup.head #head = soup.contents[0].contents[0] print head
返回內(nèi)容:hello
說明一下,contents屬性是一個列表,里面保存了該剖析樹的直接兒子。
html = soup.contents[0] # <html> ... </html> head = html.contents[0] # <head> ... </head> body = html.contents[1] # <body> ... </body>
3.獲取關(guān)系節(jié)點
使用parent獲取父節(jié)點
body = soup.body html = body.parent # html是body的父親
使用nextSibling, previousSibling獲取前后兄弟
head = body.previousSibling # head和body在同一層,是body的前一個兄弟 p1 = body.contents[0] # p1, p2都是body的兒子,我們用contents[0]取得p1 p2 = p1.nextSibling # p2與p1在同一層,是p1的后一個兄弟, 當(dāng)然body.content[1]也可得到
contents[]的靈活運用也可以尋找關(guān)系節(jié)點,尋找祖先或者子孫可以采用findParent(s), findNextSibling(s), findPreviousSibling(s)
4.find/findAll用法詳解
函數(shù)原型:find(name=None, attrs={}, recursive=True, text=None, **kwargs),findAll會返回所有符合要求的結(jié)果,并以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開頭的tag find(lambda) # 搜索函數(shù)返回結(jié)果為true的tag, 如:find(lambda name: if len(name) == 1) 搜索長度為1的tag find(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搜索
文字的搜索會導(dǎo)致其他搜索給的值如:tag, attrs都失效。方法與搜索tag一致
print p1.text # u'This is paragraphone.' print p2.text # u'This is paragraphtwo.' # 注意:1,每個tag的text包括了它以及它子孫的text。2,所有text已經(jīng)被自動轉(zhuǎn)為unicode,如果需要,可以自行轉(zhuǎn)碼encode(xxx)
recursive和limit屬性
recursive=False表示只搜索直接兒子,否則搜索整個子樹,默認為True。當(dāng)使用findAll或者類似返回list的方法時,limit屬性用于限制返回的數(shù)量,如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" title="Linux函數(shù)高級特性" >Linux函數(shù)高級特性</a> </li> <li class="listing-item"><span class="date">2014-12-02</span><a href="/post/cgdb" title="cgdb的使用" >cgdb的使用</a> </li> ... </ul>
代碼:
#!/usr/bin/env python # -*- coding: utf-8 -*- ' a http parse test programe ' __author__ = 'kuring lv' import requests import bs4 archives_url = "http://kuring.me/archive" def start_parse(url) : print "開始獲取(%s)內(nèi)容" % url response = requests.get(url) print "獲取網(wǎng)頁內(nèi)容完畢" soup = bs4.BeautifulSoup(response.content.decode("utf-8")) #soup = bs4.BeautifulSoup(response.text); # 為了防止漏掉調(diào)用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') # 當(dāng)命令行運行該模塊時,__name__等于'__main__' # 其他模塊導(dǎo)入該模塊時,__name__等于'parse_html' if __name__ == '__main__' : start_parse(archives_url)
相關(guān)文章
使用python對多個txt文件中的數(shù)據(jù)進行篩選的方法
今天小編就為大家分享一篇使用python對多個txt文件中的數(shù)據(jù)進行篩選的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-07-07Python機器學(xué)習(xí)入門(六)之Python優(yōu)化模型
這篇文章主要介紹了Python機器學(xué)習(xí)入門知識,本文給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-08-08python選取特定列 pandas iloc,loc,icol的使用詳解(列切片及行切片)
今天小編就為大家分享一篇python選取特定列 pandas iloc,loc,icol的使用詳解(列切片及行切片),具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-08-08pytorch實現(xiàn)保證每次運行使用的隨機數(shù)都相同
今天小編就為大家分享一篇pytorch實現(xiàn)保證每次運行使用的隨機數(shù)都相同,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-02-02Python中threading模塊的Lock和RLock區(qū)別詳解
這篇文章主要介紹了Python中threading模塊的Lock和RLock區(qū)別詳解,Lock鎖是Python的原始鎖,在鎖定時不屬于任何一個線程,在調(diào)用了 lock.acquire() 方法后,進入鎖定狀態(tài),lock.release()方法可以解鎖,底層是通過一個函數(shù)來實現(xiàn)的,需要的朋友可以參考下2023-09-09