Python使用BeautifulSoup庫解析網(wǎng)頁
一、BeautifulSoup的安裝與基本使用
首先,我們需要使用pip命令來安裝BeautifulSoup庫,命令如下:
pip install beautifulsoup4
安裝完成后,我們就可以開始使用BeautifulSoup來解析網(wǎng)頁了。首先,我們需要導(dǎo)入BeautifulSoup類,然后使用BeautifulSoup類的構(gòu)造方法創(chuàng)建一個BeautifulSoup對象,代碼如下:
from bs4 import BeautifulSoup html_doc = """ <html><head><title>The Dormouse's story</title></head> <body> <p class="title"><b>The Dormouse's story</b></p> """ soup = BeautifulSoup(html_doc, 'html.parser') print(soup.prettify())
二、網(wǎng)頁元素的提取
BeautifulSoup提供了一系列方法,讓我們可以輕松的提取出網(wǎng)頁中的元素。例如,我們可以使用tag.name
屬性獲取標簽的名字,tag.string
屬性獲取標簽內(nèi)的字符串,使用tag['attr']
獲取標簽的屬性,代碼如下:
from bs4 import BeautifulSoup html_doc = """ <html><head><title>The Dormouse's story</title></head> <body> <p class="title"><b>The Dormouse's story</b></p> """ soup = BeautifulSoup(html_doc, 'html.parser') title_tag = soup.title print(title_tag.name) # 輸出:title print(title_tag.string) # 輸出:The Dormouse's story
三、網(wǎng)頁元素的查找
BeautifulSoup提供了find
和find_all
方法,讓我們可以輕松的查找到網(wǎng)頁中的元素。例如,我們可以查找到所有的p
標簽,代碼如下:
from bs4 import BeautifulSoup html_doc = """ <html><head><title>The Dormouse's story</title></head> <body> <p class="title"><b>The Dormouse's story</b></p> <p class="story">Once upon a time there were three little sisters; and their names were</p> """ soup = BeautifulSoup(html_doc, 'html.parser') p_tags = soup.find_all('p') for p in p_tags: print(p.string)
四、CSS選擇器的使用
BeautifulSoup還支持CSS選擇器,我們可以使用select
方法來使用CSS選擇器選擇元素,例如:
from bs4 import BeautifulSoup html_doc = """ <html><head><title>The Dormouse's story</title></head> <body> <p class="title"><b>The Dormouse's story</b></p> <p class="story">Once upon a time there were three little sisters; and their names were</p> """ soup = BeautifulSoup(html_doc, 'html.parser') title_tag = soup.select('p.title') for title in title_tag: print(title.string)
以上就是BeautifulSoup庫的基本用法,通過BeautifulSoup,我們可以輕松地解析出網(wǎng)頁中的元素,為網(wǎng)絡(luò)爬蟲提供強大的支持,更多關(guān)于Python 網(wǎng)頁解析BeautifulSoup庫的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Python、 Pycharm、Django安裝詳細教程(圖文)
這篇文章主要介紹了Python、 Pycharm、Django安裝詳細教程,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習或者工作具有一定的參考學(xué)習價值,需要的朋友們下面隨著小編來一起學(xué)習學(xué)習吧2019-04-04Python3.6安裝及引入Requests庫的實現(xiàn)方法
下面小編就為大家分享一篇Python3.6安裝及引入Requests庫的實現(xiàn)方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-01-01python模塊與C和C++動態(tài)庫相互調(diào)用實現(xiàn)過程示例
這篇文章主要為大家介紹了python模塊與C和C++動態(tài)庫之間相互調(diào)用的實現(xiàn)過程示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助2021-11-11matplotlib圖例legend語法及設(shè)置的方法
這篇文章主要介紹了matplotlib圖例legend語法及設(shè)置的方法,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習或者工作具有一定的參考學(xué)習價值,需要的朋友們下面隨著小編來一起學(xué)習學(xué)習吧2020-07-07pytorch_detach 切斷網(wǎng)絡(luò)反傳方式
這篇文章主要介紹了pytorch_detach 切斷網(wǎng)絡(luò)反傳方式,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-05-05Django admin管理工具TabularInline類用法詳解
這篇文章主要介紹了Django admin管理工具TabularInline類用法詳解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-05-05