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