一、什麼是BS4
BeautifulSoup4,簡稱BS4,是Python的一個庫,它可以讓開發人員快速解析HTML和XML文件,從而提取出所需的信息。說白了,就是可以通過BS4快速實現爬取網頁信息的功能。
BS4最初由Leonard Richardson編寫,此後由他和John Resig共同維護,現在BS4的最新版是4.10.0,可以在官網(https://www.crummy.com/software/BeautifulSoup/bs4/doc.zh/)中進行下載和查閱。
二、為什麼要使用BS4
使用BS4有以下幾個優點:
1、簡單易用:BS4的API非常簡單、友好,無需花費太多時間就可以上手使用。
2、廣泛的應用場景:BS4可以應用於多種類型的網路爬蟲,如教育、金融、醫療、新聞等,大大提高了開發效率。
3、強大的功能:除了使用BS4進行網頁解析外,還可以通過BS4實現數據清洗、數據處理、數據分析等操作。
三、BS4的安裝和使用
為了安裝BS4需要使用pip命令,可以使用以下命令:
pip install beautifulsoup4
使用BS4的大致流程如下:
1、將HTML或XML文件載入為BeautifulSoup對象。
from bs4 import BeautifulSoup
soup = BeautifulSoup(html_doc, 'html.parser')
2、對BeautifulSoup對象進行解析,提取所需信息。
3、對所提取的信息進行處理和分析。
四、BS4的使用示例
1、解析HTML文件
1)使用requests獲取HTML文件。
import requests
url = 'https://www.baidu.com'
response = requests.get(url)
html_doc = response.content
2)將HTML文件轉化為BeautifulSoup對象。
from bs4 import BeautifulSoup
soup = BeautifulSoup(html_doc, 'html.parser')
3)解析HTML文件,並提取所需信息。
以百度首頁為例,提取其所有的鏈接。
#獲取頁面中所有的鏈接
for link in soup.find_all('a'):
print(link.get('href'))
2、解析XML文件
1)使用requests獲取XML文件。
import requests
url = 'https://www.w3school.com.cn/example/xmle/plant_catalog.xml'
response = requests.get(url)
xml_doc = response.content
2)將XML文件轉化為BeautifulSoup對象。
from bs4 import BeautifulSoup
soup = BeautifulSoup(xml_doc, 'lxml-xml')
3)解析XML文件,並提取所需信息。
以植物目錄為例,提取其所有的植物名稱。
#獲取所有植物名稱
for plant in soup.find_all('PLANT'):
print(plant.find('COMMON').text)
3、HTML標記處理
在HTML文檔中存在著各種標記,如、&、’、”等,需要進行特殊處理,否則會導致解析錯誤。BS4提供了一些方法,可以對HTML標記進行預處理。
如下面示例所示,將HTML文檔中的標記進行轉化,從而避免錯誤的解析。
#對HTML標記進行預處理
from bs4 import BeautifulSoup
import html
soup = BeautifulSoup("<p></p>", 'html.parser')
print(html.unescape(str(soup)))
4、數據清洗和處理
使用BS4可以對所爬取的數據進行清洗和處理,使得數據更加乾淨整潔,以便後續分析。如下面示例:在提取數據後,利用字元串處理方法,提取出所需信息。
#對數據進行清洗和處理
from bs4 import BeautifulSoup
import re
html_doc = """
The Dormouse's story
The Dormouse's story
Once upon a time there were three little sisters; and their names wereElsie,Lacie andTillie;and they lived at the bottom of a well.
...
"""
soup = BeautifulSoup(html_doc, 'html.parser')
#提取文本內容
text_only = soup.get_text()
#提取所有鏈接
links = soup.find_all('a')
#提取class為story的段落
story = soup.find_all('p', {'class': 'story'})
#從錨點中提取鏈接內容
for link in links:
print(link.get('href'), link.contents[0])
#通過正則表達式提取信息
for tag in soup.find_all(re.compile("^b")):
print(tag.name)
#對文本進行分詞處理
print(re.findall(r'\b\w+\b', text_only))
總結
BS4是Python中一款非常強大的網路爬蟲庫,使用BS4可以輕鬆實現對HTML和XML文件的解析,並提取出所需的數據。同時,BS4還可以對所提取的數據進行處理和分析,大大提高了網路爬蟲的開發效率。建議開發人員多加了解並使用。
原創文章,作者:KSGIL,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/316553.html