使用Beautiful Soup在Python中进行网络抓取的指南

161 阅读3分钟

今天我们将讨论如何使用Beautiful Soup库从一个HTML页面中提取内容。在提取之后,我们将使用Beautiful Soup将其转换为Python列表或字典。

什么是网页抓取,为什么我需要它?

简单的答案是这样的。不是每个网站都有API来获取内容。你可能想从你最喜欢的烹饪网站获取食谱,或者从一个旅游博客获取照片。在没有API的情况下,提取HTML,或刮削,可能是获得这些内容的唯一方法。我将向你展示如何用Python做这件事。

并非所有的网站都对搜刮有好感,有些网站可能明确禁止搜刮。请向网站所有者查询他们是否同意刮削。

如何在Python中抓取一个网站?

为了在Python中进行网络刮削,我们要执行三个基本步骤。

  1. 使用requests 库提取 HTML 内容。
  2. 分析HTML结构,确定有我们内容的标签。
  3. 使用Beautiful Soup提取标签,并将数据放到Python列表中。

安装库

让我们首先安装我们需要的库。requests 库从网站上获取HTML内容。Beautiful Soup解析HTML并将其转换为Python对象。要为 Python 3 安装这些库,请运行。

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中提取我们的数据,我们需要确定哪些标签有我们需要的内容。

如果你浏览一下HTML,你会发现靠近顶部的这一部分。

<div class="col">
  <a href="/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 contenth5>
        <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 2021small>
      div>
    div>
  a>
div>

这是整个页面中每篇文章都会重复的部分。我们可以看到,.card-title 有文章标题,.card-text 有摘录,.card-footer > small 有发布日期。

让我们用Beautiful Soup来提取这些。

#!/usr/bin/python3
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 ,以漂亮地打印输出,但你可以在你的代码中跳过它。将上面的代码保存在一个名为fetch.py 的文件中,然后用运行它。

python3 fetch.py

如果一切顺利,你应该看到这个。

[{'excerpt': "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.',
'pub_date': 'Aug 2021',
'title': 'Using variables in Jekyll to define custom content'},
{'excerpt': "In this article, I'll highlight some ideas for Jekyll"
'collections, blog category pages, responsive web-design, and'
'netlify.toml to make static website maintenance a breeze.',
'pub_date': 'Jul 2021',
'title': 'The evolution of ayushsharma.in: Jekyll, Bootstrap, Netlify,'
'static websites, and responsive design.'},
{'excerpt': "These are the top 5 lessons I've learned after 5 years of"
'Terraform-ing.',
'pub_date': 'Jul 2021',
'title': '5 key best practices for sane and usable Terraform setups'},
... (truncated)

这就是它所需要的一切!在22行代码中,我们已经在Python中建立了一个网络刮削器。你可以在我的例子库中找到源代码

结论

有了Python列表中的网站内容,我们现在可以用它做一些很酷的事情。我们可以把它作为JSON返回给另一个应用程序,或者把它转换成带有自定义样式的HTML。请随意复制粘贴上述代码,用你最喜欢的网站做实验。

玩得开心,并继续编码。