python?中的?BeautifulSoup?網(wǎng)頁使用方法解析
一、安裝
- Bautiful Soup 是第三方庫,因此需要單獨下載,下載方式非常簡單
- 由于 BS4 解析頁面時需要依賴文檔解析器,所以還需要安裝 lxml 作為解析庫
- Python 也自帶了一個文檔解析庫 html.parser, 但是其解析速度要稍慢于 lxml
pip install bs4 pip install lxml pip install html5lib
二、html.parser解析
- html.parser 表示解析文檔時所用的解析器
- 解析器也可以是 lxml 或者 html5lib
html = ''' <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal">×</button> <h4 class="modal-title">Modal title</h4> </div> <div class="modal-body"> ... </div> <div class="modal-footer"> <a href="#" rel="external nofollow" rel="external nofollow" class="btn btn-default" data-dismiss="modal">Close</a> <a href="#" rel="external nofollow" rel="external nofollow" class="btn btn-primary">Save</a> </div> </div> </div> ''' from bs4 import BeautifulSoup soup = BeautifulSoup(html, 'html.parser') #prettify()用于格式化輸出html/xml文檔 print(soup.prettify())
三、外部文檔解析
- 外部文檔,您也可以通過 open 的方式打開讀取
from bs4 import BeautifulSoup
fp = open('html_doc.html', encoding='utf8')
soup = BeautifulSoup(fp, 'lxml')四、標(biāo)簽選擇器
- 標(biāo)簽(Tag)是組成 HTML 文檔的基本元素
- 通過標(biāo)簽名和標(biāo)簽屬性可以提取出想要的內(nèi)容
from bs4 import BeautifulSoup
soup = BeautifulSoup('<p class="name nickname user"><b>i am autofelix</b></p>', 'html.parser')
#獲取整個p標(biāo)簽的html代碼
print(soup.p)
#獲取b標(biāo)簽
print(soup.p.b)
#獲取p標(biāo)簽內(nèi)容,使用NavigableString類中的string、text、get_text()
print(soup.p.text)
#返回一個字典,里面是多有屬性和值
print(soup.p.attrs)
#查看返回的數(shù)據(jù)類型
print(type(soup.p))
#根據(jù)屬性,獲取標(biāo)簽的屬性值,返回值為列表
print(soup.p['class'])
#給class屬性賦值,此時屬性值由列表轉(zhuǎn)換為字符串
soup.p['class']=['Web','Site']
print(soup.p)五、css選擇器
- 支持大部分的 CSS 選擇器,比如常見的標(biāo)簽選擇器、類選擇器、id 選擇器,以及層級選擇器
- 通過向 select 方法中添加選擇器,就可以在 HTML 文檔中搜索到與之對應(yīng)的內(nèi)容
html = """
<html>
<head>
<title>零基礎(chǔ)學(xué)編程</title>
</head>
<body>
<p class="intro"><b>i am autofelix</b></p>
<p class="nickname">飛兔小哥</p>
<a rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" id="csdn">csdn主頁</a>
<a rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" id="infoq">infoq主頁</a>
<a rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" id="51cto">51cto主頁</a>
<p class="attention">跪求關(guān)注 一鍵三連</p>
<p class="introduce">
<a rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" id="cnblogs">博客園主頁</a>
</p>
</body>
</html>
"""
from bs4 import BeautifulSoup
soup = BeautifulSoup(html, 'html.parser')
#根據(jù)元素標(biāo)簽查找
print(soup.select('nickname'))
#根據(jù)屬性選擇器查找
print(soup.select('a[href]'))
#根據(jù)類查找
print(soup.select('.attention'))
#后代節(jié)點查找
print(soup.select('html head title'))
#查找兄弟節(jié)點
print(soup.select('p + a'))
#根據(jù)id選擇p標(biāo)簽的兄弟節(jié)點
print(soup.select('p ~ #csdn'))
#nth-of-type(n)選擇器,用于匹配同類型中的第n個同級兄弟元素
print(soup.select('p ~ a:nth-of-type(1)'))
#查找子節(jié)點
print(soup.select('p > a'))
print(soup.select('.introduce > #cnblogs'))六、節(jié)點遍歷
- 可以使用 contents、children 用來遍歷子節(jié)點
- 可以使用 parent 與 parents 用來遍歷父節(jié)點
- 可以使用 next_sibling 與 previous_sibling 用來遍歷兄弟節(jié)點
html = """ <html> <head> <title>零基礎(chǔ)學(xué)編程</title> </head> <body> <p class="intro"><b>i am autofelix</b></p> <p class="nickname">飛兔小哥</p> <a rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" id="csdn">csdn主頁</a> <a rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" id="infoq">infoq主頁</a> <a rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" id="51cto">51cto主頁</a> <p class="attention">跪求關(guān)注 一鍵三連</p> <p class="introduce"> <a rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" id="cnblogs">博客園主頁</a> </p> </body> </html> """ from bs4 import BeautifulSoup soup = BeautifulSoup(html, 'html.parser') body_tag=soup.body print(body_tag) # 以列表的形式輸出,所有子節(jié)點 print(body_tag.contents) # children 用來遍歷子節(jié)點 for child in body_tag.children: print(child)
七、find_all方法
- 是解析 HTML 文檔的常用方法
- find_all() 方法用來搜索當(dāng)前 tag 的所有子節(jié)點
- 并判斷這些節(jié)點是否符合過濾條件
- 最后以列表形式將符合條件的內(nèi)容返回
html = """
<html>
<head>
<title>零基礎(chǔ)學(xué)編程</title>
</head>
<body>
<p class="intro"><b>i am autofelix</b></p>
<p class="nickname">飛兔小哥</p>
<a rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" id="csdn">csdn主頁</a>
<a rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" id="infoq">infoq主頁</a>
<a rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" id="51cto">51cto主頁</a>
<p class="attention">跪求關(guān)注 一鍵三連</p>
<p class="introduce">
<a rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" id="cnblogs">博客園主頁</a>
</p>
</body>
</html>
"""
import re
from bs4 import BeautifulSoup
# 創(chuàng)建soup解析對象
soup = BeautifulSoup(html, 'html.parser')
# 查找所有a標(biāo)簽并返回
print(soup.find_all("a"))
# 查找前兩條a標(biāo)簽并返回,只返回兩條a標(biāo)簽
print(soup.find_all("a",limit=2))
# 按照標(biāo)簽屬性以及屬性值查找
print(soup.find_all("p",class_="nickname"))
print(soup.find_all(id="infoq"))
# 列表行書查找tag標(biāo)簽
print(soup.find_all(['b','a']))
# 正則表達式匹配id屬性值
print(soup.find_all('a',id=re.compile(r'.\d')))
print(soup.find_all(id=True))
# True可以匹配任何值,下面代碼會查找所有tag,并返回相應(yīng)的tag名稱
for tag in soup.find_all(True):
print(tag.name,end=" ")
# 輸出所有以b開始的tag標(biāo)簽
for tag in soup.find_all(re.compile("^b")):
print(tag.name)
# 簡化前寫法
soup.find_all("a")
# 簡化后寫法
soup("a")八、find方法
html = """
<html>
<head>
<title>零基礎(chǔ)學(xué)編程</title>
</head>
<body>
<p class="intro"><b>i am autofelix</b></p>
<p class="nickname">飛兔小哥</p>
<a rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" id="csdn">csdn主頁</a>
<a rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" id="infoq">infoq主頁</a>
<a rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" id="51cto">51cto主頁</a>
<p class="attention">跪求關(guān)注 一鍵三連</p>
<p class="introduce">
<a rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" id="cnblogs">博客園主頁</a>
</p>
</body>
</html>
"""
import re
from bs4 import BeautifulSoup
# 創(chuàng)建soup解析對象
soup = BeautifulSoup(html, 'html.parser')
# 查找第一個a并直接返回結(jié)果
print(soup.find('a'))
# 查找title
print(soup.find('intro'))
# 匹配指定href屬性的a標(biāo)簽
print(soup.find('a',))
# 根據(jù)屬性值正則匹配
print(soup.find(class_=re.compile('tro')))
# attrs參數(shù)值
print(soup.find(attrs={'class': 'introduce'}))
# 使用 find 時,如果沒有找到查詢標(biāo)簽會返回 None,而 find_all 方法返回空列表
print(soup.find('aa'))
print(soup.find_all('bb'))
# 簡化寫法
print(soup.head.title)
# 上面代碼等價于
print(soup.find("head").find("title"))到此這篇關(guān)于python 中的 BeautifulSoup 網(wǎng)頁解析的文章就介紹到這了,更多相關(guān)BeautifulSoup 網(wǎng)頁內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python實現(xiàn)基于TCP UDP協(xié)議的IPv4 IPv6模式客戶端和服務(wù)端功能示例
這篇文章主要介紹了Python實現(xiàn)基于TCP UDP協(xié)議的IPv4 IPv6模式客戶端和服務(wù)端功能,結(jié)合實例形式分析了Python基于TCP UDP協(xié)議的IPv4 IPv6模式客戶端和服務(wù)端數(shù)據(jù)發(fā)送與接收相關(guān)操作技巧,需要的朋友可以參考下2018-03-03
一篇文章帶你了解python標(biāo)準(zhǔn)庫--os模塊
在本篇內(nèi)容里小編給大家整理的是關(guān)于Python中os模塊及用法相關(guān)知識點,有興趣的朋友們可以學(xué)習(xí)下,希望能給你帶來幫助2021-08-08
python爬蟲學(xué)習(xí)筆記--BeautifulSoup4庫的使用詳解
這篇文章主要介紹了Python中使用Beautiful Soup庫的超詳細教程,示例代碼基于Python2.x版本,極力推薦!需要的朋友可以參考下2021-08-08
基于python SMTP實現(xiàn)自動發(fā)送郵件教程解析
這篇文章主要介紹了基于python實現(xiàn)自動發(fā)送郵件教程解析,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-06-06
淺談Scrapy網(wǎng)絡(luò)爬蟲框架的工作原理和數(shù)據(jù)采集
在python爬蟲中:requests + selenium 可以解決目前90%的爬蟲需求,難道scrapy 是解決剩下的10%的嗎?顯然不是。scrapy框架是為了讓我們的爬蟲更強大、更高效。接下來我們一起學(xué)習(xí)一下它吧。2019-02-02
pytorch和tensorflow計算Flops和params的詳細過程
這篇文章主要介紹了pytorch和tensorflow計算Flops和params,本文通過實例代碼給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-08-08

