跳過到頁腳內容
PYTHON 說明

Python 中的 Requests Library:教學

在 Web 開發和資料獲取等多元化的環境中,Python 是一種卓越的語言。 它簡單易用,再加上強大的庫支持,使其成為處理 HTTP 請求的理想選擇。 在這些庫中,Python Requests模組脫穎而出,成為與 Web 服務互動的多功能且使用者友好的工具。

在本文中,我們將探討 HTTP 請求的基礎知識,並探討Requests函式庫如何幫助 Python 開發人員有效率地處理這些請求。 我們也將探討如何將 HTTP 請求與 IronPDF 等 Python 函式庫結合使用,從而輕鬆產生和編輯 PDF 檔案。

了解 HTTP 請求

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

一個HTTP請求通常包含以下幾個部分:

  1. HTTP 方法:指定客戶端要執行的 HTTP 請求操作。常用方法包括 GET、POST、PUT、DELETE 等。
  2. URL :統一資源定位符,用於標識所要求的資源。 3.請求標頭:隨請求傳送的附加訊息,例如身分驗證憑證、內容類型等。 4.正文:透過 POST 或 PUT 請求傳送的資料。

請求庫簡介

Python 中的Requests函式庫簡化了發出 HTTP 請求的過程。 它提供了一個優雅直覺的 API,可以無縫地發送各種類型的請求並處理回應。

Requests Python(開發者使用指南):圖 1 - Requests 函式庫網頁,包含安裝說明

讓我們來看一些基本的使用範例,但首先,讓我們來看看安裝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 中,產生類似https://api.example.com/data?key=value¶m2=value2的請求 URL。

將 Requests 與 IronPDF 整合以產生 PDF 文件

在深入探討實現之前,讓我們先簡單了解 IronPDF。

IronPDF - Python PDF 函式庫

IronPDF for Python 是一個流行的 Python 庫,用於產生、讀取、編輯和操作 PDF 文件。 它提供了一系列豐富的功能,可以透過程式設計方式建立專業外觀的 PDF 檔案。

Python 請求(開發者使用方法):圖 2 - IronPDF 網頁

若要使用 IronPDF 和透過 Requests 取得的內容產生 PDF,請依照下列步驟操作:

步驟 1:安裝 IronPDF

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

pip install ironpdf
pip install ironpdf
SHELL

步驟二:使用 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 可以輕鬆與 Web 進行交互,使開發人員能夠更專注於建立優秀的應用程序,而不是處理 HTTP 通訊的複雜性。

進階用法

您可以使用 IronPDF 的強大功能,透過自訂 PDF 設定、邊距、方向、影像、CSS、JavaScript 等,進一步增強 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")
# 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 取得資料、與 Web 服務互動或抓取網頁,Requests 都能憑藉其直覺的 API 和強大的功能簡化 HTTP 請求流程。

將 Python 版 IronPDF 與 Python 中的 Requests 結合使用,為從獲取的內容動態生成 PDF 文件開闢了無限可能。 透過按照本文概述的步驟並探索 IronPDF 和 Requests 的高級功能,Python 開發人員可以簡化其 PDF 生成工作流程,並產生符合其特定要求的高品質文件。

Python 請求(開發者使用指南):圖 3 - IronPDF 許可頁面

IronPDF非常適合企業使用。 IronPDF 提供免費試用版,起價僅為$799 ,並提供退款保證,是您管理文件的安全選擇。 立即下載 IronPDF,體驗無縫的 PDF 整合!

Curtis Chau
技術作家

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

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