跳至頁尾內容
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請求輸出

在URLs中發送參數

通常,您需要將參數傳遞給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 - Get請求輸出

處理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輸出

處理Headers

Headers對HTTP請求至關重要。 您可以這樣新增自定義headers到您的請求中:

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 - Header輸出

文件上傳

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 - Post請求輸出

介紹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 程式庫是任何需要與Web API交互的Python開發人員的必備工具。其簡單性和易用性使其成為發送HTTP請求的首選。 當與IronPDF結合使用時,它打開了更多的可能性,允許您從網頁中抓取資料並將其轉換為專業品質的PDF文件。 無論您是在建立報告、發票還是歸檔網頁內容,Requests 和IronPDF的結合為您的PDF生成需求提供了強大的解決方案。

關於IronPDF授權的進一步資訊,請參閱IronPDF授權頁。 您也可以探索我們的詳細教程,了解更多關於HTML轉PDF轉換的見解。

Curtis Chau
技術作家

Curtis Chau擁有Carleton大學的電腦科學學士學位,專精於前端開發,擁有Node.js、TypeScript、JavaScript和React的專業知識。Curtis熱衷於建立直觀且美觀的使用者介面,喜愛使用現代框架並建立結構良好、視覺吸引力的手冊。

除了開發,Curtis對物聯網(IoT)有濃厚的興趣,探索創新的方法來整合硬體和軟體。在空閒時間,他喜歡玩遊戲和建立Discord機器人,結合他對技術的熱愛與創造力。

Iron 支援團隊

我們線上24小時,每週5天。
聊天
電子郵件
給我打電話