Python爬蟲beautifulsoup4常用的解析方法總結(jié)
摘要
- 如何用beautifulsoup4解析各種情況的網(wǎng)頁
beautifulsoup4的使用
關(guān)于beautifulsoup4,官網(wǎng)已經(jīng)講的很詳細了,我這里就把一些常用的解析方法做個總結(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,因為效率高,當然需要pip install lxml一下。
當然這三種解析方式在某些情況解析得到的對象內(nèi)容是不同的,比如對于標簽不完整這一情況(p標簽只有一半):
soup = BeautifulSoup("<a></p>", "html.parser")
# 只有起始標簽的會自動補全,只有結(jié)束標簽的灰自動忽略
# 結(jié)果為:<a></a>
soup = BeautifulSoup("<a></p>", "lxml")
#結(jié)果為:<html><body><a></a></body></html>
soup = BeautifulSoup("<a></p>", "html5lib")
# html5lib則出現(xiàn)一般的標簽都會自動補全
# 結(jié)果為:<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標簽內(nèi)的所有內(nèi)容
soup.find(class_="title")
#或者
soup.find("p",class_="title" id = "p1")
#獲取class為title的p標簽的文本內(nèi)容"The Dormouse's story"
soup.find(class_="title").get_text()
#獲取文本內(nèi)容時可以指定不同標簽之間的分隔符,也可以選擇是否去掉前后的空白。
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標簽的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內(nèi)的所有a標簽
soup.select("p > #link1") #P標簽內(nèi),按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
需要轉(zhuǎn)碼
- AttributeError: ‘NoneType' object has no attribute ‘foo'
沒這個屬性
就介紹這么多,應該可以覆蓋大部分網(wǎng)頁結(jié)構(gòu)了吧~!
總結(jié)
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學習或者工作具有一定的參考學習價值,謝謝大家對腳本之家的支持。如果你想了解更多相關(guān)內(nèi)容請查看下面相關(guān)鏈接
相關(guān)文章
棧和隊列數(shù)據(jù)結(jié)構(gòu)的基本概念及其相關(guān)的Python實現(xiàn)
這篇文章主要介紹了棧和隊列數(shù)據(jù)結(jié)構(gòu)的基本概念及其相關(guān)的Python實現(xiàn),先進先出和后進先出的知識也已經(jīng)成為了計算機學習中的老生常談了:D需要的朋友可以參考下2015-08-08
Python softmax實現(xiàn)及數(shù)值穩(wěn)定性詳解
這篇文章主要為大家介紹了Python softmax實現(xiàn)及數(shù)值穩(wěn)定性詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-07-07
Python實現(xiàn)將多個文件的名稱或后綴名由大寫改為小寫
這篇文章主要介紹了如何基于Python語言實現(xiàn)將多個文件的名稱或后綴名由大寫字母修改為小寫,文中的示例代碼講解詳細,感興趣的可以了解下2023-09-09

