跳過到頁腳內容
PYTHON 幫助

Python 请求库(开发者如何工作)

Python 因其簡單性和可讀性而廣受讚譽,使其成為開發者在網絡爬蟲和與 API 互動中的一個熱門選擇。使這些互動成為可能的關鍵庫之一是 Python Requests 庫。 Requests 是一個用于 Python 的 HTTP 請求庫,可讓您輕鬆發送 HTTP 請求。 在本文中,我們將深入探討 Python Requests 庫的功能,通過實際示例探索其用法,並介紹 IronPDF,展示如何將其與 Requests 結合來創建和操作網絡數據中的 PDF。

介紹 Requests

Python Requests 庫被創建是為了讓 HTTP 請求變得更簡單和更人性化。 它將製作請求的複雜性抽象為簡單的 API,使您可以專注於與網絡上的服務和數據互動。 無論您需要抓取網頁、交互 REST API、禁用 SSL 證書驗證或將數據發送到服務器,Requests 庫都能滿足您的需求。

關鍵特點
  1. 簡單性:易於使用和理解的語法。
  2. HTTP 方法:支持所有 HTTP 方法 - GET、POST、PUT、DELETE 等。
  3. 會話對象:在請求之間保持 cookie。
  4. 身份驗證:簡化添加身份驗證標頭。
  5. 代理:支持 HTTP 代理。
  6. 超時:有效管理請求超時。
  7. SSL 驗證:默認情況下驗證 SSL 證書。

安裝 Requests

要開始使用 Requests,您需要安裝它。 這可以使用 pip 完成:

pip install requests
pip install requests
SHELL

基本用法

這是如何使用 Requests 擷取網頁的一個簡單示例:

import requests

# Send a GET request to the specified URL
response = requests.get('https://www.example.com')

# Print the status code of the response (e.g., 200 for success)
print(response.status_code)

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

# Send a GET request to the specified URL
response = requests.get('https://www.example.com')

# Print the status code of the response (e.g., 200 for success)
print(response.status_code)

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

Python Requests Library(它如何為開發者工作):圖 1 - 發送 HTTP 請求輸出

在 URL 中發送參數

通常,您需要將參數傳遞到 URL。 Python Requests 模塊通過 params 關鍵字使這一操作變得簡便:

import requests

# Define the parameters to be sent in the URL
params = {'key1': 'value1', 'key2': 'value2'}

# Send a GET request with parameters
response = requests.get('https://www.example.com', params=params)

# Print the full URL including the parameters
print(response.url)
import requests

# Define the parameters to be sent in the URL
params = {'key1': 'value1', 'key2': 'value2'}

# Send a GET request with parameters
response = requests.get('https://www.example.com', params=params)

# Print the full URL including the parameters
print(response.url)
PYTHON

Python Requests Library(它如何為開發者工作):圖 2 - 獲取請求輸出

處理 JSON 數據

與 API 交互通常涉及 JSON 數據。 Requests 通過內置的 JSON 支持簡化了這一過程:

import requests

# Send a GET request to retrieve JSON data
response = requests.get('https://jsonplaceholder.typicode.com/todos/1')

# Convert the JSON response to a Python dictionary
data = response.json()

# Print the JSON data
print(data)
import requests

# Send a GET request to retrieve JSON data
response = requests.get('https://jsonplaceholder.typicode.com/todos/1')

# Convert the JSON response to a Python dictionary
data = response.json()

# Print the JSON data
print(data)
PYTHON

Python Requests Library(它如何為開發者工作):圖 3 - JSON 輸出

處理標頭

標頭對於 HTTP 請求至關重要。 您可以像這樣向您的請求添加自定義標頭:

import requests

# Define custom headers
headers = {'User-Agent': 'my-app/0.0.1'}

# Send a GET request with custom headers
response = requests.get('https://www.example.com', headers=headers)

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

# Define custom headers
headers = {'User-Agent': 'my-app/0.0.1'}

# Send a GET request with custom headers
response = requests.get('https://www.example.com', headers=headers)

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

Python Requests Library(它如何為開發者工作):圖 4 - 標頭輸出

文件上傳

Requests 也支持文件上傳。 這是您可以如何上傳文件:

import requests

# Define the files to be uploaded
files = {'file': open('report.txt', 'rb')}

# Send a POST request with the file
response = requests.post('https://www.example.com/upload', files=files)

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

# Define the files to be uploaded
files = {'file': open('report.txt', 'rb')}

# Send a POST request with the file
response = requests.post('https://www.example.com/upload', files=files)

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

Python Requests Library(它如何為開發者工作):圖 5 - 發送請求輸出

介紹 IronPDF for Python

IronPDF 是一個多功能的 PDF 創建庫,可以用來在您的 Python 應用中創建、編輯和操作 PDF。 當您需要將 HTML 內容生成 PDF 時,它尤其有用,是創建報告、發票或任何需要以便攜格式分發的文檔的絕佳工具。

安裝 IronPDF

要安裝 IronPDF,請使用 pip:

 pip install ironpdf

Python Requests Library(它如何為開發者工作):圖 6 - IronPDF

將 IronPDF 與 Requests 配合使用

結合使用 Requests 和 IronPDF 可以讓您從網絡上獲取數據並直接將其轉換為 PDF 文檔。 這對於從網絡數據創建報告或將網頁保存為 PDF 特別有用。

這是一個使用 Requests 擷取網頁,然後使用 IronPDF 將其保存為 PDF 的示例:

import requests
from ironpdf import ChromePdfRenderer

# Fetch a web page
url = 'https://www.example.com'
response = requests.get(url)

if response.status_code == 200:
    # Extract the HTML content from the response
    html_content = response.text

    # Initialize the PDF renderer
    renderer = ChromePdfRenderer()

    # Render the HTML content as a PDF
    pdf = renderer.RenderHtmlAsPdf(html_content)

    # Save the generated PDF to a file
    pdf.save('output.pdf')
    print('PDF created successfully')
else:
    # Print an error message if the request was not successful
    print(f'Failed to retrieve the webpage. Status code: {response.status_code}')
import requests
from ironpdf import ChromePdfRenderer

# Fetch a web page
url = 'https://www.example.com'
response = requests.get(url)

if response.status_code == 200:
    # Extract the HTML content from the response
    html_content = response.text

    # Initialize the PDF renderer
    renderer = ChromePdfRenderer()

    # Render the HTML content as a PDF
    pdf = renderer.RenderHtmlAsPdf(html_content)

    # Save the generated PDF to a file
    pdf.save('output.pdf')
    print('PDF created successfully')
else:
    # Print an error message if the request was not successful
    print(f'Failed to retrieve the webpage. Status code: {response.status_code}')
PYTHON

此腳本首先使用 Requests 抓取指定 URL 的 HTML 內容。 然後使用 IronPDF 將這個響應對象的 HTML 內容轉換為 PDF,並將生成的 PDF 保存到文件中。

Python Requests Library(它如何為開發者工作):圖 7 - PDF 輸出

結論

Requests 庫是任何需要與網絡 API 交互的 Python 開發者的基本工具。它的簡單性和易用性使其成為製作 HTTP 請求的首選。 當與 IronPDF 結合使用時,它創造了更多可能性,讓您能夠從網絡上獲取數據並將其轉換為專業品質的 PDF 文檔。 無論您是在創建報告、發票,還是存檔網絡內容,Requests 和 IronPDF 的組合為您的 PDF 生成需求提供了一個強大的解決方案。

有關 IronPDF 許可的更多信息,請參閱 IronPDF 許可頁面。 您還可以瀏覽我們的詳細 HTML 到 PDF 轉換教程以獲得更多洞見。

Curtis Chau
技術作家

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

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