今天小編就為大家分享一篇關於Python爬蟲beautifulsoup4常用的解析方法總結,小編覺得內容挺不錯的,現在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧
摘要
如何用beautifulsoup4解析各種情況的網頁
beautifulsoup4的使用
關於beautifulsoup4,官網已經講的很詳細了,我這里就把一些常用的解析方法做個總結,方便查閱。
裝載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類時,需要加入兩個參數,第一個參數即是我們爬到html源碼,第二個參數是html解析器,常用的有三個解析器,分別是”html.parser”,”lxml”,”html5lib”,官網推薦用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則出現一般的標簽都會自動補全
# 結果為:<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')
#根據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參數,recursive=False時,只find當前標簽的第一級子標簽的數據
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())
#獲取特定數量的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,需要根據其屬性來定義獲取規則
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的兄弟節點
soup.select("#link1 + .sister")
soup.select(".sister") #按class名稱查
soup.select("#sister") #按id名稱查
soup.select('a[href="http://example.com/elsie" rel="external nofollow" ]') # 按標簽的屬性查
soup.select('a[href$="tillie"]')
soup.select_one(".sister")
注意幾個可能出現的錯誤,可以用try捕獲來防止爬蟲進程
UnicodeEncodeError: ‘charmap’ codec can’t encode character u’\xfoo’ in position bar (或其它類型的 UnicodeEncodeError
需要轉碼
AttributeError: ‘NoneType’ object has no attribute ‘foo’
沒這個屬性
注意:很多人學Python過程中會遇到各種煩惱問題解決不了。為此小編建了個Python全棧免費答疑交流.裙 : 624440745不懂的問題有老司機解決里面還有最新Python教程項目可拿,,一起相互監督共同進步!
本文的文字及圖片來源於網絡加上自己的想法,僅供學習、交流使用,不具有任何商業用途,版權歸原作者所有,如有問題請及時聯系我們以作處理。