如何使用 BeautifulSoup 程序包来解析 Python 中网页中的数据?


BeautifulSoup 是一个第三方 Python 库,用于从网页解析数据。它有助于进行网络抓取,这是一个从不同资源中抓取、使用和操作数据的过程。

网络抓取也可以用于提取数据以进行研究目的,了解/比较市场趋势,执行 SEO 监控等等。

可以在 Windows 上运行以下代码行以安装 BeautifulSoup −

pip install beautifulsoup4

让我们看一个例子 −

示例

import requests
from bs4 import BeautifulSoup
from urllib.request import urlopen
import urllib
url = 'https://en.wikipedia.org/wiki/Algorithm'
html = urlopen(url).read()
print("Reading the webpage...")
soup = BeautifulSoup(html, features="html.parser")
print("Parsing the webpage...")
for script in soup(["script", "style"]):
   script.extract() # rip it out
print("Extracting text from the webpage...")
text = soup.get_text()
print("Data cleaning...")
lines = (line.strip() for line in text.splitlines())
chunks = (phrase.strip() for line in lines for phrase in line.split(" "))
text = '\n'.join(chunk for chunk in chunks if chunk)
text = str(text)
print(text)

输出

Reading the webpage...
Parsing the webpage...
Extracting text from the webpage...
Data cleaning...
Recursive C implementation of Euclid's algorithm from the above flowchart
Recursion
A recursive algorithm is one that invokes (makes reference to) itself repeatedly until a certain condition (also known as termination condition) matches, which is a method common to functional programming….
…..
Developers
Statistics
Cookie statement

说明

  • 导入了所需包,并进行了别名设置。

  • 定义了网站。

  • 打开了 URL,并删除了“脚本”标签和其他无关的 HTML 标签。

  • 使用“get_text”函数从网页数据中提取文本。

  • 消除了额外的空格和无效的词语。

  • 文本打印在控制台上。

更新时间: 2021-01-18

273 次浏览

启动您的 职业

通过完成课程获得认证

开始
广告
© . All rights reserved.