App下載

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

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

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

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

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

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

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

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

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

安裝庫(kù)

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

pip3 install requests beautifulsoup4

提取 HTML

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

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

https://notes.ayushsharma.in/technology

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

#!/usr/bin/python3
import requests

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

data = requests.get(url)

print(data.text)

該變量data將包含頁(yè)面的 HTML 源代碼。

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

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

如果您瀏覽 HTML,您會(huì)在頂部附近找到此部分:

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>

這是在每篇文章的整個(gè)頁(yè)面中重復(fù)的部分。我們可以看到.card-title有文章標(biāo)題、.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漂亮打印輸出,但您可以在自己的代碼中跳過(guò)它。將上面的代碼保存在一個(gè)名為 的文件中fetch.py,然后使用以下命令運(yùn)行它:

python3 fetch.py

如果一切順利,您應(yīng)該會(huì)看到:

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

結(jié)論

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


0 人點(diǎn)贊