Python爬蟲beautifulsoup4常用的解析方法總結(jié)
摘要
- 如何用beautifulsoup4解析各種情況的網(wǎng)頁
beautifulsoup4的使用
關(guān)于beautifulsoup4,官網(wǎng)已經(jīng)講的很詳細(xì)了,我這里就把一些常用的解析方法做個總結(jié),方便查閱。
裝載html文檔
使用beautifulsoup的第一步是把html文檔裝載到beautifulsoup中,使其形成一個beautifulsoup對象。
import requests from bs4 import BeautifulSoup url = "http://new.qq.com/omn/20180705/20180705A0920X.html" r = requests.get(url) htmls = r.text #print(htmls) soup = BeautifulSoup(htmls, 'html.parser')
初始化BeautifulSoup類時,需要加入兩個參數(shù),第一個參數(shù)即是我們爬到html源碼,第二個參數(shù)是html解析器,常用的有三個解析器,分別是”html.parser”,”lxml”,”html5lib”,官網(wǎng)推薦用lxml,因為效率高,當(dāng)然需要pip install lxml一下。
當(dāng)然這三種解析方式在某些情況解析得到的對象內(nèi)容是不同的,比如對于標(biāo)簽不完整這一情況(p標(biāo)簽只有一半):
soup = BeautifulSoup("<a></p>", "html.parser") # 只有起始標(biāo)簽的會自動補(bǔ)全,只有結(jié)束標(biāo)簽的灰自動忽略 # 結(jié)果為:<a></a> soup = BeautifulSoup("<a></p>", "lxml") #結(jié)果為:<html><body><a></a></body></html> soup = BeautifulSoup("<a></p>", "html5lib") # html5lib則出現(xiàn)一般的標(biāo)簽都會自動補(bǔ)全 # 結(jié)果為:<html><head></head><body><a><p></p></a></body></html>
使用
在使用中,我盡量按照我使用的頻率介紹,畢竟為了查閱~
- 按照標(biāo)簽名稱、id、class等信息獲取某個標(biāo)簽
html = '<p class="title" id="p1"><b>The Dormouses story</b></p>' soup = BeautifulSoup(html, 'lxml') #根據(jù)class的名稱獲取p標(biāo)簽內(nèi)的所有內(nèi)容 soup.find(class_="title") #或者 soup.find("p",class_="title" id = "p1") #獲取class為title的p標(biāo)簽的文本內(nèi)容"The Dormouse's story" soup.find(class_="title").get_text() #獲取文本內(nèi)容時可以指定不同標(biāo)簽之間的分隔符,也可以選擇是否去掉前后的空白。 soup = BeautifulSoup('<p class="title" id="p1"><b> The Dormouses story </b></p><p class="title" id="p1"><b>The Dormouses story</b></p>', "html5lib") soup.find(class_="title").get_text("|", strip=True) #結(jié)果為:The Dormouses story|The Dormouses story #獲取class為title的p標(biāo)簽的id soup.find(class_="title").get("id") #對class名稱正則: soup.find_all(class_=re.compile("tit")) #recursive參數(shù),recursive=False時,只find當(dāng)前標(biāo)簽的第一級子標(biāo)簽的數(shù)據(jù) soup = BeautifulSoup('<html><head><title>abc','lxml') soup.html.find_all("title", recursive=False)
- 按照標(biāo)簽名稱、id、class等信息獲取多個標(biāo)簽
soup = BeautifulSoup('<p class="title" id="p1"><b> The like story </b></p><p class="title" id="p1"><b>The Dormouses story</b></p>', "html5lib") #獲取所有class為title的標(biāo)簽 for i in soup.find_all(class_="title"): print(i.get_text()) #獲取特定數(shù)量的class為title的標(biāo)簽 for i in soup.find_all(class_="title",limit = 2): print(i.get_text())
- 按照標(biāo)簽的其他屬性獲取某個標(biāo)簽
html = '<a alog-action="qb-ask-uname" href="/usercent" rel="external nofollow" target="_blank">蝸牛宋</a>' soup = BeautifulSoup(html, 'lxml') # 獲取"蝸牛宋",此時,該標(biāo)簽里既沒有class也沒有id,需要根據(jù)其屬性來定義獲取規(guī)則 author = soup.find('a',{"alog-action":"qb-ask-uname"}).get_text() #或 author = soup.find(attrs={"alog-action": "qb-ask-uname"})
- 找前頭和后頭的標(biāo)簽
soup.find_all_previous("p") soup.find_previous("p") soup.find_all_next("p") soup.find_next("p")
- 找父標(biāo)簽
soup.find_parents("div") soup.find_parent("div")
- css選擇器
soup.select("title") #標(biāo)簽名 soup.select("html head title") #多級標(biāo)簽名 soup.select("p > a") #p內(nèi)的所有a標(biāo)簽 soup.select("p > #link1") #P標(biāo)簽內(nèi),按id查標(biāo)簽 soup.select("#link1 ~ .sister") #查找相同class的兄弟節(jié)點 soup.select("#link1 + .sister") soup.select(".sister") #按class名稱查 soup.select("#sister") #按id名稱查 soup.select('a[ rel="external nofollow" ]') # 按標(biāo)簽的屬性查 soup.select('a[href$="tillie"]') soup.select_one(".sister")
注意幾個可能出現(xiàn)的錯誤,可以用try捕獲來防止爬蟲進(jìn)程
- UnicodeEncodeError: ‘charmap' codec can't encode character u'\xfoo' in position bar (或其它類型的 UnicodeEncodeError
需要轉(zhuǎn)碼
- AttributeError: ‘NoneType' object has no attribute ‘foo'
沒這個屬性
就介紹這么多,應(yīng)該可以覆蓋大部分網(wǎng)頁結(jié)構(gòu)了吧~!
總結(jié)
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,謝謝大家對腳本之家的支持。如果你想了解更多相關(guān)內(nèi)容請查看下面相關(guān)鏈接
相關(guān)文章
python實現(xiàn)在無須過多援引的情況下創(chuàng)建字典的方法
這篇文章主要介紹了python實現(xiàn)在無須過多援引的情況下創(chuàng)建字典的方法,是非常實用的技巧,需要的朋友可以參考下2014-09-09Pandas統(tǒng)計計數(shù)value_counts()的使用
本文主要介紹了Pandas統(tǒng)計計數(shù)value_counts()的使用,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-07-07pytorch中Tensor.to(device)和model.to(device)的區(qū)別及說明
這篇文章主要介紹了pytorch中Tensor.to(device)和model.to(device)的區(qū)別及說明,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-07-07