博客 / 詳情

返回

Python 網頁解析初級篇:BeautifulSoup庫的入門使用

在Python的網絡爬蟲中,網頁解析是一項重要的技術。而在眾多的網頁解析庫中,BeautifulSoup庫憑藉其簡單易用而廣受歡迎。在本篇文章中,我們將學習BeautifulSoup庫的基本用法。

一、BeautifulSoup的安裝與基本使用

首先,我們需要使用pip命令來安裝BeautifulSoup庫,命令如下:

pip install beautifulsoup4

安裝完成後,我們就可以開始使用BeautifulSoup來解析網頁了。首先,我們需要導入BeautifulSoup類,然後使用BeautifulSoup類的構造方法創建一個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())

二、網頁元素的提取

BeautifulSoup提供了一系列方法,讓我們可以輕鬆的提取出網頁中的元素。例如,我們可以使用tag.name屬性獲取標籤的名字,tag.string屬性獲取標籤內的字符串,使用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

三、網頁元素的查找

BeautifulSoup提供了findfind_all方法,讓我們可以輕鬆的查找到網頁中的元素。例如,我們可以查找到所有的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,我們可以輕鬆地解析出網頁中的元素,為網絡爬蟲提供強大的支持。

user avatar
0 位用戶收藏了這個故事!

發佈 評論

Some HTML is okay.