温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

使用BeautifulSoup在Python中抓取网页内容的方法

发布时间:2022-01-26 09:15:18 来源:亿速云 阅读:231 作者:iii 栏目:开发技术

本文小编为大家详细介绍“使用BeautifulSoup在Python中抓取网页内容的方法”,内容详细,步骤清晰,细节处理妥当,希望这篇“使用BeautifulSoup在Python中抓取网页内容的方法”文章能帮助大家解决疑惑,下面跟着小编的思路慢慢深入,一起来学习新知识吧。

什么是网页抓取?

简单的答案是:并非每个网站都有用于获取内容的 API。您可能想从您最喜欢的烹饪网站获取食谱或从旅游博客获取照片。如果没有 API,提取 HTML 或抓取可能是获取该内容的唯一方法。我将向您展示如何在 Python 中执行此操作。

注意:并非所有网站都喜欢抓取,有些网站可能会明确禁止。与网站所有者核对是否可以抓取。

如何在 Python 中抓取网站?

为了让网络抓取在 Python 中工作,我们将执行 3 个基本步骤:

  1. 使用请求库提取 HTML 内容。

  2. 分析 HTML 结构并识别包含我们内容的标签。

  3. 使用 BeautifulSoup 提取标签并将数据放入 Python 列表中。

安装库

让我们首先安装我们需要的库。请求从网站获取 HTML 内容。BeautifulSoup 解析 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 中提取内容

要从 中接收到的 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">
        <h6 class="card-title">Using variables in Jekyll to define custom content</h6>
        <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)

读到这里,这篇“使用BeautifulSoup在Python中抓取网页内容的方法”文章已经介绍完毕,想要掌握这篇文章的知识点还需要大家自己动手实践使用过才能领会,如果想了解更多相关内容的文章,欢迎关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI