一、什么是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/n/316553.html