Python Beautiful Soup 刮取简易指南,


Python 中的 Beautiful Soup 库可以很方便的从网页中提取 HTML 内容。

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

什么是 Web 刮取,为什么我需要它?

答案很简单:并非每个网站都有获取内容的 API。你可能想从你最喜欢的烹饪网站上获取食谱,或者从旅游博客上获取照片。如果没有 API,提取 HTML(或者说 刮取scraping 可能是获取内容的唯一方法。我将向你展示如何使用 Python 来获取。

并非所以网站都喜欢被刮取,有些网站可能会明确禁止。请于网站所有者确认是否同意刮取。

Python 如何刮取网站?

使用 Python 进行刮取,我们将执行三个基本步骤:

安装库

首先安装我们需要的库。requests 库从网站获取 HTML 内容,Beautiful Soup 解析 HTML 并将其转换为 Python 对象。在 Python3 中安装它们,运行:

  1. pip3 install requests beautifulsoup4

提取 HTML

在本例中,我将选择刮取网站的 Techhology 部分。如果你跳转到此页面,你会看到带有标题、摘录和发布日期的文章列表。我们的目标是创建一个包含这些信息的文章列表。

网站页面的完整 URL 是:

  1. https://notes.ayushsharma.in/technology

我们可以使用 requests 从这个页面获取 HTML 内容:

  1. #!/usr/bin/python3
  2. import requests
  3.  
  4. url = 'https://notes.ayushsharma.in/technology'
  5.  
  6. data = requests.get(url)
  7.  
  8. print(data.text)

变量 data 将包含页面的 HTML 源代码。

从 HTML 中提取内容

为了从 data 中提取数据,我们需要确定哪些标签具有我们需要的内容。

如果你浏览 HTML,你会发现靠近顶部的这一段:

  1. <div class="col">
  2. <a href="/2021/08/using-variables-in-jekyll-to-define-custom-content" class="post-card">
  3. <div class="card">
  4. <div class="card-body">
  5. <h5 class="card-title">Using variables in Jekyll to define custom content</h5>
  6. <small class="card-text text-muted">I recently discovered that Jekyll's config.yml can be used to define custom
  7. variables for reusing content. I feel like I've been living under a rock all this time. But to err over and
  8. over again is human.</small>
  9. </div>
  10. <div class="card-footer text-end">
  11. <small class="text-muted">Aug 2021</small>
  12. </div>
  13. </div>
  14. </a>
  15. </div>

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

让我们使用 Beautiful Soup 提取这些内容。

  1. #!/usr/bin/python3
  2. import requests
  3. from bs4 import BeautifulSoup
  4. from pprint import pprint
  5.  
  6. url = 'https://notes.ayushsharma.in/technology'
  7. data = requests.get(url)
  8.  
  9. my_data = []
  10.  
  11. html = BeautifulSoup(data.text, 'html.parser')
  12. articles = html.select('a.post-card')
  13.  
  14. for article in articles:
  15.  
  16. title = article.select('.card-title')[0].get_text()
  17. excerpt = article.select('.card-text')[0].get_text()
  18. pub_date = article.select('.card-footer small')[0].get_text()
  19.  
  20. my_data.append({"title": title, "excerpt": excerpt, "pub_date": pub_date})
  21.  
  22. pprint(my_data)

以上代码提取文章信息并将它们放入 my_data 变量中。我使用了 pprint 来美化输出,但你可以在代码中忽略它。将上面的代码保存在一个名为 fetch.py 的文件中,然后运行它:

  1. python3 fetch.py

如果一切顺利,你应该会看到:

  1. [{'excerpt': "I recently discovered that Jekyll's config.yml can be used to"
  2. "define custom variables for reusing content. I feel like I've"
  3. 'been living under a rock all this time. But to err over and over'
  4. 'again is human.',
  5. 'pub_date': 'Aug 2021',
  6. 'title': 'Using variables in Jekyll to define custom content'},
  7. {'excerpt': "In this article, I'll highlight some ideas for Jekyll"
  8. 'collections, blog category pages, responsive web-design, and'
  9. 'netlify.toml to make static website maintenance a breeze.',
  10. 'pub_date': 'Jul 2021',
  11. 'title': 'The evolution of ayushsharma.in: Jekyll, Bootstrap, Netlify,'
  12. 'static websites, and responsive design.'},
  13. {'excerpt': "These are the top 5 lessons I've learned after 5 years of"
  14. 'Terraform-ing.',
  15. 'pub_date': 'Jul 2021',
  16. 'title': '5 key best practices for sane and usable Terraform setups'},
  17.  
  18. ... (truncated)

以上是全部内容!在这 22 行代码中,我们用 Python 构建了一个网络刮取器,你可以在 我的示例仓库中找到源代码。

总结

对于 Python 列表中的网站内容,我们现在可以用它做一些很酷的事情。我们可以将它作为 JSON 返回给另一个应用程序,或者使用自定义样式将其转换为 HTML。随意复制粘贴以上代码并在你最喜欢的网站上进行试验。

玩的开心,继续编码吧。

评论关闭