跳至页脚内容
PYTHON 帮助

Python Requests 库(开发者如何使用)

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. 会话对象:在请求之间保持cookies。
  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 (How It Works For Developers): Figure 1 - Making HTTP Requests Output

在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 (How It Works For Developers): Figure 2 - Get Request Output

处理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 (How It Works For Developers): Figure 3 - JSON Output

处理请求头

请求头对于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 (How It Works For Developers): Figure 4 - Header Output

文件上传

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 (How It Works For Developers): Figure 5 - Post Request Output

介绍IronPDF for Python

IronPDF是一个功能强大的PDF生成库,可用于在Python应用程序中创建、编辑和操作PDF。 它特别适用于需要从HTML内容生成PDF的场景,成为创建报告、发票或任何需要以便携格式分发的文档的出色工具。

安装 IronPDF

要安装IronPDF,可使用pip:

 pip install ironpdf

Python Requests Library (How It Works For Developers): Figure 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 (How It Works For Developers): Figure 7 - PDF Output

结论

Requests库是任何需要与Web API交互的Python开发人员的基本工具。其简单性和易用性使其成为进行HTTP请求的首选。 当与IronPDF结合使用时,它开启了更多可能性,使您能够从网上获取数据并将其转换为专业质量的PDF文件。 无论您是在创建报告、发票还是存档网页内容,Requests与IronPDF的组合为您的PDF生成需求提供了一个强大的解决方案。

有关IronPDF许可的更多信息,请参考IronPDF许可页面。 您还可以浏览我们关于HTML转PDF转换的详细教程以获取更多见解。

Curtis Chau
技术作家

Curtis Chau 拥有卡尔顿大学的计算机科学学士学位,专注于前端开发,精通 Node.js、TypeScript、JavaScript 和 React。他热衷于打造直观且美观的用户界面,喜欢使用现代框架并创建结构良好、视觉吸引力强的手册。

除了开发之外,Curtis 对物联网 (IoT) 有浓厚的兴趣,探索将硬件和软件集成的新方法。在空闲时间,他喜欢玩游戏和构建 Discord 机器人,将他对技术的热爱与创造力相结合。