国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁(yè) > 編程 > Python > 正文

Python爬蟲beautifulsoup4常用的解析方法總結(jié)

2020-02-16 01:21:21
字體:
來(lái)源:轉(zhuǎn)載
供稿:網(wǎng)友

摘要

如何用beautifulsoup4解析各種情況的網(wǎng)頁(yè)

beautifulsoup4的使用

關(guān)于beautifulsoup4,官網(wǎng)已經(jīng)講的很詳細(xì)了,我這里就把一些常用的解析方法做個(gè)總結(jié),方便查閱。

裝載html文檔

使用beautifulsoup的第一步是把html文檔裝載到beautifulsoup中,使其形成一個(gè)beautifulsoup對(duì)象。

import requestsfrom bs4 import BeautifulSoupurl = "http://new.qq.com/omn/20180705/20180705A0920X.html"r = requests.get(url)htmls = r.text#print(htmls)soup = BeautifulSoup(htmls, 'html.parser')

初始化BeautifulSoup類時(shí),需要加入兩個(gè)參數(shù),第一個(gè)參數(shù)即是我們爬到html源碼,第二個(gè)參數(shù)是html解析器,常用的有三個(gè)解析器,分別是”html.parser”,”lxml”,”html5lib”,官網(wǎng)推薦用lxml,因?yàn)樾矢?,?dāng)然需要pip install lxml一下。

當(dāng)然這三種解析方式在某些情況解析得到的對(duì)象內(nèi)容是不同的,比如對(duì)于標(biāo)簽不完整這一情況(p標(biāo)簽只有一半):

soup = BeautifulSoup("<a></p>", "html.parser")# 只有起始標(biāo)簽的會(huì)自動(dòng)補(bǔ)全,只有結(jié)束標(biāo)簽的灰自動(dòng)忽略# 結(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)簽都會(huì)自動(dòng)補(bǔ)全# 結(jié)果為:<html><head></head><body><a><p></p></a></body></html>

使用

在使用中,我盡量按照我使用的頻率介紹,畢竟為了查閱~

按照標(biāo)簽名稱、id、class等信息獲取某個(gè)標(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)容時(shí)可以指定不同標(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)簽的idsoup.find(class_="title").get("id")#對(duì)class名稱正則:soup.find_all(class_=re.compile("tit"))#recursive參數(shù),recursive=False時(shí),只find當(dāng)前標(biāo)簽的第一級(jí)子標(biāo)簽的數(shù)據(jù)soup = BeautifulSoup('<html><head><title>abc','lxml')soup.html.find_all("title", recursive=False)
按照標(biāo)簽名稱、id、class等信息獲取多個(gè)標(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())            
發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 莫力| 德格县| 贺州市| 尼木县| 伊宁市| 刚察县| 牡丹江市| 阳高县| 安庆市| 巴里| 栾城县| 延寿县| 上高县| 琼海市| 易门县| 永福县| 舒城县| 铜山县| 丰台区| 略阳县| 高尔夫| 建阳市| 库伦旗| 南部县| 布尔津县| 宁乡县| 曲松县| 宝山区| 佛坪县| 化德县| 西青区| 同江市| 彩票| 阆中市| 镇江市| 昭通市| 米泉市| 卓资县| 西乌珠穆沁旗| 德令哈市| 松原市|