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

166 阅读4分钟

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

如何使用BeautifulSoup库从HTML页面中提取内容。在提取之后,我们将用BeautifulSoup将其转换为Python的列表或字典!

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

什么是Web Scraping,以及为什么我需要它?

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

注意:并不是所有的网站都对搜刮有兴趣,有些网站可能明确禁止搜刮。请向网站所有者查询他们是否同意刮削。

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

为了使网络刮削在Python中工作,我们将执行3个基本步骤。

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

安装库

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

pip3 install requests beautifulsoup4

提取HTML

在这个例子中,我将选择抓取我网站的技术部分。如果你去那个页面,你会看到一个带有标题、节选和出版日期的文章列表。我们的目标是创建一个包含这些信息的文章列表。

技术页面的完整URL是。

https://notes.ayushsharma.in/technology

我们可以使用Requests .NET来获取这个页面的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,你会在顶部附近找到这个部分。

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 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 有发布日期。

让我们用BeautifulSoup来提取这些内容。

Python

#!/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

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

Python


[{'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。请随意复制粘贴上述代码,用你最喜欢的网站做实验。

玩得开心点,继续编写代码 :)

经Ayush Sharma, DZone MVB许可发表于DZone:点击这里查看原文。