共计 1914 个字符,预计需要花费 5 分钟才能阅读完成。
导读 | 本文讨论如何使用 Beautiful Soup 库从 HTML 页面中提取内容。提取后,我们将使用 Beautiful Soup 将其转换为 Python 列表或字典。 |
为了让网络抓取在 Python 中工作,我们将执行三个基本步骤:
使用 requests
库提取 HTML 内容。
分析 HTML 结构并识别包含内容的标签。
使用 Beautiful Soup 提取标签并将数据放入 Python 列表中。
安装库
首先安装我们需要的库。requests
库可以从网站获取 HTML 内容。Beautiful Soup 解析 HTML 并将其转换为 Python 对象。在 Python 3 中需要安装下面两个库:
[root@localhost ~]# pip3 install requests beautifulsoup4
提取 html
本文抓取该网站的技术页面。如果你转到该页面,将看到带有标题、摘录和发布日期的文章列表。我们的目标是创建一个包含该信息的文章列表。
技术页面的完整 URL 是:
https://notes.ayushsharma.in/technology
我们可以使用 requests
从这个页面获取 HTML 内容:
#!/usr/bin/python3 | |
import requests | |
url = 'https://notes.ayushsharma.in/technology' | |
data = requests.get(url) | |
print(data.text) |
变量 data
将包含页面的 HTML 源代码。
从 HTML 中提取内容
为了从 data 中提取我们的数据,我们需要确定哪些标签具有我们需要的内容。
如果你浏览 HTML,会在顶部附近找到此部分:
<div class="col"> | |
<a href="https://www.linuxprobe.com/2021/08/using-variables-in-jekyll-to-define-custom-content" class="post-card"> | |
<div class="card"> | |
<div class="card-body"> | |
<h5 class="card-title">Using variables in Jekyll to define custom content</h5> | |
<small class="card-text text-muted">I recently discovered that Jekyll's config.yml can be used to define custom | |
variables for reusing content. I feel like I've been living under a rock all this time. But to err over and | |
over again is human.</small> | |
</div> | |
<div class="card-footer text-end"> | |
<small class="text-muted">Aug 2021</small> | |
</div> | |
</div> | |
</a> | |
</div> |
这是在每篇文章的整个页面中重复的部分。我们可以看到 .card-title
有文章标题,.card-text
有摘录, .card-footer
类下面的 small
标签 有发布日期。
让我们使用 Beautiful Soup 提取这些内容。
import requests | |
from bs4 import BeautifulSoup | |
from pprint import pprint | |
url = 'https://notes.ayushsharma.in/technology' | |
data = requests.get(url) | |
my_data = [] | |
html = BeautifulSoup(data.text, 'html.parser') | |
articles = html.select('a.post-card') | |
for article in articles: | |
title = article.select('.card-title')[0].get_text() | |
excerpt = article.select('.card-text')[0].get_text() | |
pub_date = article.select('.card-footer small')[0].get_text() | |
my_data.append({"title": title, "excerpt": excerpt, "pub_date": pub_date}) | |
pprint(my_data) |
上面的代码提取文章并将它们放入 my_data 变量中。我正在使用 pprint 来打印输出。
总结
我们可以将它作为 JSON 返回给另一个应用程序,或者使用自定义样式将其转换为 HTML。
正文完
星哥玩云-微信公众号
