跳過到頁腳內容
PYTHON 幫助

Python 中的请求库:教程

在網頁開發和資料擷取的多樣化環境中,Python 是一種卓越的語言。 其簡單性,加上強大的函式庫,使其成為處理 HTTP 請求的理想選擇。 在這些函式庫中,Python 的 Requests 模組以其多功能且使用者友善的特性,成為與網路服務互動的卓越工具。

在本文中,我們將探討 HTTP 請求的基礎,並了解 Requests 函式庫如何有效地幫助 Python 開發者處理它們。 我們還將探討如何使用 IronPDF for Python 等函式庫來處理 HTTP 請求,這使得 PDF 的生成和編輯變得輕而易舉。

了解 HTTP 請求

HTTP(超文本傳輸協定)是全球資訊網上資料傳輸的基礎。 它是一種協定,用於管理客戶端(網頁瀏覽器)和伺服器之間的超文本(如 HTML)的傳輸。 HTTP 作為一種請求-回應協定運作,客戶端向伺服器發送請求,伺服器回應請求的資源。

一個 HTTP 請求通常包含幾個組件:

  1. HTTP 方法:指定客戶端想要執行的操作以發出 HTTP 請求。常見的方法包括 GET、POST、PUT、DELETE 等。
  2. URL:統一資源定位符,識別正在請求的資源。
  3. 請求標頭:與請求一起發送的附加資訊,例如驗證憑據、內容類型等。
  4. 主體:與 POST 或 PUT 請求一起發送的資料。

介紹 Requests 函式庫

Python 中的 Requests 函式庫簡化了 HTTP 請求的發送過程。 它提供了一個優雅且直觀的 API,用於順利發送各種類型的請求和處理回應。

Requests Python(對開發人員的工作原理):圖 1 - 請求函式庫的網頁,其中包含安裝說明

讓我們了解一些基本的使用範例,但首先,讓我們看看如何安裝 Requests 模組。

安裝

在使用 Requests 函式庫之前,請確保它已安裝。 您可以透過 pip 安裝它:

pip install requests
pip install requests
SHELL

發送 GET 請求

使用 requests.get() 方法在此處向指定的 URL 發送 GET 請求:

import requests

# Make a GET request to the URL
response = requests.get('https://api.example.com/data')

# Print the response text (content of the response)
print(response.text)
import requests

# Make a GET request to the URL
response = requests.get('https://api.example.com/data')

# Print the response text (content of the response)
print(response.text)
PYTHON

以下代碼將向指定的 URL https://api.example.com/data 發送 GET 請求並列印回應主體。

發送 POST 請求

要發送包含資料的 POST 請求,請使用 requests.post() 方法:

import requests

# Data to send in the POST request
data = {'key': 'value'}

# Make a POST request with data
response = requests.post('https://api.example.com/post', data=data)

# Print the response in JSON format
print(response.json())
import requests

# Data to send in the POST request
data = {'key': 'value'}

# Make a POST request with data
response = requests.post('https://api.example.com/post', data=data)

# Print the response in JSON format
print(response.json())
PYTHON

在這裡,我們向 https://api.example.com/post 發送含 JSON 資料的 POST 請求,並列印 JSON 回應資料。

處理回應對象

HTTP 請求返回的回應對象提供了各種屬性和方法,以訪問回應的不同方面,例如 HTTP 標頭、狀態代碼、內容等。例如:

import requests

# Make a GET request
response = requests.get('https://api.example.com/data')

# Print the status code of the response
print(response.status_code)

# Print the response headers
print(response.headers)
import requests

# Make a GET request
response = requests.get('https://api.example.com/data')

# Print the status code of the response
print(response.status_code)

# Print the response headers
print(response.headers)
PYTHON

錯誤處理

在發送 HTTP 請求時,優雅地處理錯誤至關重要。 Requests 函式庫透過引發例外來簡化錯誤處理,適用於常見錯誤,例如連接錯誤和逾時。 例如:

import requests

try:
    # Make a GET request
    response = requests.get('https://api.example.com/data')

    # Raise an exception for HTTP errors
    response.raise_for_status()
except requests.exceptions.HTTPError as err:
    # Print the error message
    print(err)
import requests

try:
    # Make a GET request
    response = requests.get('https://api.example.com/data')

    # Raise an exception for HTTP errors
    response.raise_for_status()
except requests.exceptions.HTTPError as err:
    # Print the error message
    print(err)
PYTHON

禁用 SSL 憑證驗證

requests 函式庫中,您可以通過在您的請求中將 verify 參數設定為 False 來禁用 SSL 憑證驗證:

import requests

# Make a GET request with SSL verification disabled
response = requests.get('https://api.example.com/data', verify=False)

# Process the response
print(response.text)
import requests

# Make a GET request with SSL verification disabled
response = requests.get('https://api.example.com/data', verify=False)

# Process the response
print(response.text)
PYTHON

包含查詢字串

您還可以透過使用 params 參數將查詢參數附加到 URL 中:

import requests

# Define query parameters
params = {'key': 'value', 'param2': 'value2'}

# Make a GET request with query parameters
response = requests.get('https://api.example.com/data', params=params)

# Process the response
print(response.text)
import requests

# Define query parameters
params = {'key': 'value', 'param2': 'value2'}

# Make a GET request with query parameters
response = requests.get('https://api.example.com/data', params=params)

# Process the response
print(response.text)
PYTHON

在此範例中,params 字典包含查詢參數。 當發送 GET 請求時,這些參數會自動附加到 URL 中,結果是請求 URL 如 https://api.example.com/data?key=value&param2=value2

將 Requests 與 IronPDF 整合生成 PDF

在進入實作之前,讓我們簡單了解 IronPDF。

IronPDF - Python PDF 函式庫

IronPDF for Python 是一個流行的 Python 函式庫,用於生成、閱讀、編輯和操作 PDF 文件。 它提供了一組豐富的功能來程式化地創建專業外觀的 PDF。

Requests Python(對開發人員的工作原理):圖 2 - IronPDF 網頁

要使用 Requests 擷取的內容與 IronPDF 生成 PDF,請按照以下步驟進行:

步驟 1:安裝 IronPDF

首先,確保在您的 Python 環境中安裝了 IronPDF。 您可以透過 pip 安裝它:

pip install ironpdf
pip install ironpdf
SHELL

步驟 2:使用 Requests 擷取內容

使用 Requests 函式庫擷取您想要包含在 PDF 中的內容。 例如:

import requests

# Make a GET request to fetch data
response = requests.get('https://api.example.com/data')
data = response.text
import requests

# Make a GET request to fetch data
response = requests.get('https://api.example.com/data')
data = response.text
PYTHON

步驟 3:使用 IronPDF 生成 PDF

一旦您得到內容,請使用 IronPDF 生成 PDF。 這裡有一個基本的範例:

from ironpdf import ChromePdfRenderer

# Instantiate Renderer
renderer = ChromePdfRenderer()

# Create a PDF from the data received from requests
pdf = renderer.RenderHtmlAsPdf(data)

# Export to a file
pdf.SaveAs("output.pdf")
from ironpdf import ChromePdfRenderer

# Instantiate Renderer
renderer = ChromePdfRenderer()

# Create a PDF from the data received from requests
pdf = renderer.RenderHtmlAsPdf(data)

# Export to a file
pdf.SaveAs("output.pdf")
PYTHON

在此範例中,data 包含透過 Requests 擷取的 HTML 內容。 IronPDF 的 RenderHtmlAsPdf() 方法將此 HTML 內容轉換為 PDF 文件。 最後,使用 SaveAs() 方法將 PDF 儲存到檔案。

利用 Requests 函式庫,Python 讓網絡互動變得如行雲流水,使開發者可以更專注於構建出色的應用程式,而不必處理 HTTP 通信的複雜性。

進階用法

您可以進一步增強 PDF 生成過程,透過使用 IronPDF 的廣泛功能自訂 PDF 設定、頁邊距、方向、圖片、CSS、JavaScript 等。 例如:

# Set page margins
renderer.RenderingOptions.MarginTop = 40  # millimeters
renderer.RenderingOptions.MarginLeft = 20  # millimeters
renderer.RenderingOptions.MarginRight = 20  # millimeters
renderer.RenderingOptions.MarginBottom = 40  # millimeters

# Example with HTML Assets
# Load external HTML assets: Images, CSS, and JavaScript.
# An optional BasePath 'C:\\site\\assets\\' is set as the file location to load assets from
my_advanced_pdf = renderer.RenderHtmlAsPdf("<img src='icons/iron.png'>", "C:\\site\\assets")
my_advanced_pdf.SaveAs("html-with-assets.pdf")
# Set page margins
renderer.RenderingOptions.MarginTop = 40  # millimeters
renderer.RenderingOptions.MarginLeft = 20  # millimeters
renderer.RenderingOptions.MarginRight = 20  # millimeters
renderer.RenderingOptions.MarginBottom = 40  # millimeters

# Example with HTML Assets
# Load external HTML assets: Images, CSS, and JavaScript.
# An optional BasePath 'C:\\site\\assets\\' is set as the file location to load assets from
my_advanced_pdf = renderer.RenderHtmlAsPdf("<img src='icons/iron.png'>", "C:\\site\\assets")
my_advanced_pdf.SaveAs("html-with-assets.pdf")
PYTHON

在此處,我們設定頁邊距並從基礎目錄中添加圖片,然後將其儲存到檔案中。

有關 IronPDF 功能和功能的更多資訊,請訪問文檔頁面,並查看這些現成的代碼例子以與 Python 集成。

結論

Python 中的 Requests 函式庫為發送 HTTP 請求提供了強大而簡單的介面。 無論您是從 API 擷取資料、與網絡服務互動還是抓取網頁,Requests 以其直觀的 API 和強大的功能簡化了 HTTP 請求流程。

將 IronPDF for Python 與 Requests 結合使用,為動態生成從擷取內容生成的 PDF 文件開啟了新的可能性。 通過按照本文中概述的步驟並探索 IronPDF 和 Requests 的高級功能,Python 開發者可以簡化其 PDF 生成工作流程,並生成量身定制以滿足其特定需求的高品質文件。

Requests Python(對開發人員的工作原理):圖 3 - IronPDF 授權頁面

IronPDF 非常適合企業使用。 試用 IronPDF 的免費試用版,從 $799 開始,並且有退款保證,這是管理您文件的安全選擇。 立即下載 IronPDF,體驗無縫的 PDF 集成!

Curtis Chau
技術作家

Curtis Chau 擁有卡爾頓大學計算機科學學士學位,專注於前端開發,擅長於 Node.js、TypeScript、JavaScript 和 React。Curtis 熱衷於創建直觀且美觀的用戶界面,喜歡使用現代框架並打造結構良好、視覺吸引人的手冊。

除了開發之外,Curtis 對物聯網 (IoT) 有著濃厚的興趣,探索將硬體和軟體結合的創新方式。在閒暇時間,他喜愛遊戲並構建 Discord 機器人,結合科技與創意的樂趣。