App下載

如何使用BeautifulSoup在Python中抓取網(wǎng)頁內(nèi)容?使用BeautifulSoup抓取網(wǎng)頁的指南!

花開一夜 2021-09-16 13:55:03 瀏覽數(shù) (4268)
反饋

今天我們將討論如何使用 BeautifulSoup 庫從 HTML 頁面中提取內(nèi)容。提取后,我們將使用 BeautifulSoup 將其轉(zhuǎn)換為 Python 列表或字典!

什么是網(wǎng)頁抓???

簡單的答案是:并非每個網(wǎng)站都有用于獲取內(nèi)容的 API。您可能想從您最喜歡的烹飪網(wǎng)站獲取食譜或從旅游博客獲取照片。如果沒有 API,提取 HTML 或抓取可能是獲取該內(nèi)容的唯一方法。我將向您展示如何在 Python 中執(zhí)行此操作。

注意:并非所有網(wǎng)站都喜歡抓取,有些網(wǎng)站可能會明確禁止。與網(wǎng)站所有者核對是否可以抓取。

如何在 Python 中抓取網(wǎng)站?

為了讓網(wǎng)絡(luò)抓取在 Python 中工作,我們將執(zhí)行 3 個基本步驟:

  1. 使用請求庫提取 HTML 內(nèi)容。
  2. 分析 HTML 結(jié)構(gòu)并識別包含我們內(nèi)容的標簽。
  3. 使用 BeautifulSoup 提取標簽并將數(shù)據(jù)放入 Python 列表中。

安裝庫

讓我們首先安裝我們需要的庫。請求從網(wǎng)站獲取 HTML 內(nèi)容。BeautifulSoup 解析 HTML 并將其轉(zhuǎn)換為 Python 對象。要為 Python 3 安裝這些,請運行:

pip3 install requests beautifulsoup4

提取 HTML

在這個例子中,我將選擇抓取網(wǎng)站的技術(shù)部分。如果您轉(zhuǎn)到該頁面,您將看到一個包含標題、摘錄和發(fā)布日期的文章列表。我們的目標是創(chuàng)建一個包含該信息的文章列表。

技術(shù)頁面的完整 URL 是:

https://notes.ayushsharma.in/technology

我們可以使用 Requests 從此頁面獲取 HTML 內(nèi)容:

#!/usr/bin/python3
import requests

url = 'https://notes.ayushsharma.in/technology'

data = requests.get(url)

print(data.text)

該變量data將包含頁面的 HTML 源代碼。

從 HTML 中提取內(nèi)容

要從 中接收到的 HTML 中提取我們的數(shù)據(jù)data,我們需要確定哪些標簽具有我們需要的內(nèi)容。

如果您瀏覽 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發(fā)布日期。

讓我們使用 BeautifulSoup 提取這些內(nèi)容。

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 構(gòu)建了一個網(wǎng)絡(luò)爬蟲。您可以在我的示例 repo 中找到源代碼

結(jié)論

使用 Python 列表中的網(wǎng)站內(nèi)容,我們現(xiàn)在可以用它做很酷的事情。我們可以將它作為 JSON 返回給另一個應用程序,或者使用自定義樣式將其轉(zhuǎn)換為 HTML。隨意復制粘貼上面的代碼并在您最喜歡的網(wǎng)站上進行試驗。


0 人點贊