使用 Python 进行 Web 请求

发布日期:2026-07-20 01:04:02  来源 : 杭州电子商务研究院    浏览量 :0
杭州电子商务研究院 发布日期:2026-07-20 01:04:02  
0

介绍

互联网是一个巨大的数据源,网站通常会提供 RESTful API端点(URL、URI)以通过 HTTP 请求共享数据。HTTP 请求由 GET、POST、PUT、DELETE 等方法组成,用于操作和访问资源或数据。网站通常需要注册过程才能访问 RESTful API,或者根本不提供 API。因此,为了简化流程,我们还可以将数据下载为原始文本并对其进行格式化。例如,无需注册即可从个人博客或 GitHub 用户的个人资料信息中下载内容。本指南将解释使用Requests包及其各种功能在 Python 中发出 Web 请求的过程。

先决条件

  1. Python 设置:从python.org下载并安装 python 设置,或者您可以使用jupyter notebook在浏览器中运行 python 。
  2. 请求包:在终端(命令提示符)中使用 python 包管理器 (pip) 命令来安装包。
      pip3 install requests
    

对于 Python 2(直到 Python 3.4),请使用pip。Python还提供Virtualenv来跨多个应用程序分别管理依赖项和开发环境。

发出 Get 请求

为了进行 REST 调用,第一步是在当前环境中导入 python请求模块。

      import requests                                 # To use request package in current program 
response = requests.get("www.dummyurl.com")     # To execute get request
    

Python 还提供了使用as关键字创建联盟的方法

      import requests as reqs 
response = reqs.get('https://www.google.com')
    

为了发出第一个请求,我们将使用JSONPlaceholder API,该 API 为特定项目(如帖子、待办事项和相册)提供 JSON 响应。因此,/todos/1 API 将响应 TODO 项的详细信息。

      url = 'https://jsonplaceholder.typicode.com/todos/1' 
response = requests.get(url)        # To execute get request 
print(response.status_code)     # To print http response code  
print(response.text)            # To print formatted JSON response
    

上述代码片段的执行将提供结果:

      200 
{ 
  "userId": 1, 
  "id": 1, 
  "title": "delectus aut autem", 
  "completed": false 
}
    

状态代码200表示请求成功执行,并且response.content将返回 TODO 项的实际 JSON 响应。

有许多公共 API可用于测试 REST 调用。您还可以使用Postman Echomocky返回自定义响应和标头,以及为生成的虚拟链接添加延迟。

POST 请求

Post 请求更安全,因为它们可以以加密形式将数据作为消息正文携带。GET 请求将参数附加在 URL 中,这也可以在浏览器历史记录中看到,而 SSL/TLS 和 HTTPS 连接也会加密 GET 参数。如果您不使用 HTTPs 或 SSL/TSL 连接,则 POST 请求是安全的首选。
可以使用字典对象将数据作为键值对作为第二个参数发送到post方法。

      data = {'title':'Python Requests','body':'Requests are awesome','userId':1} 
response = requests.post('https://jsonplaceholder.typicode.com/posts', data) 
print(response.status_code) 
print(response.text)
    

该虚拟发布请求将返回附加数据作为响应主体:

      201 
{ 
  "title": "Python Requests", 
  "body": "Requests are awesome", 
  "userId": "1", 
  "id": 101 
}
    

POST 请求对数据长度没有限制,因此更适合文件和图像。而 GET 请求限制为 2 KB(某些服务器可以处理 64 KB 数据),并且 GET 仅允许 ASCII 值。

post一样,请求也支持其他方法,如putdelete等。任何请求都可以在不包含任何数据的情况下发送,并且可以定义空的占位符名称以增强代码清晰度。

      response = req.post('https://jsonplaceholder.typicode.com/posts', data = None, json = dictionaryObject) 
print(response.json())      # output: {'id': 101}
    

在这种情况下,如果数据设置为None,则可以跳过此操作,因为它由于默认值而自动发生。

响应类型

响应对象可以解析为字符串,字节,JSON 或原始格式:

      print(response.content)           # To print response bytes 
print(response.text)              # To print unicode response string 
jsonRes = response.json()         # To get response dictionary as JSON 
print(jsonRes['title'] , jsonRes['body'], sep = ' : ')  # output: Python Requests : Requests are awesome
    

将响应读取为原始值使我们能够读取特定数量的字节,并且为了启用此功能,请将stream = True设置为请求方法中的参数。

      data = {'title':'Pyton Requests','body':'Requests are qwesome','userId':1} 
response = req.post('https://jsonplaceholder.typicode.com/posts', data, stream = True) 
print(response.raw.read(30))     # output: b'{\n  "title": "Python Requests"'
    

要启用流,必须特别提及流占位符,因为它不是必需的参数。

您还可以使用iter_content方法自动解码gzip文件。

      response.iter_content(chunk_size=1024)
    

验证

许多 API 都需要身份验证过程才能访问用户特定的详细信息。请求支持各种类型的身份验证,例如:

  • 基本身份验证:这将以base64编码(文本为字节)传输身份验证详细信息,这意味着没有加密和安全性。它适用于内置安全性的 HTTPs 或 SSL/TSL 启用连接。
      # Open github API to test authentication 
from requests.auth import HTTPBasicAuth     
requests.get('https://api.github.com/user', auth=HTTPBasicAuth('userName', 'password')) 
 
# or shortcut method 
requests.get('https://api.github.com/user', auth=('user', 'pass'))
    
  • 摘要式身份验证:通过对凭证、HTTP 方法、随机数(服务器提供的一次性数字)和请求的 URI 应用哈希函数,以加密形式传输凭证。因此,在进行 HTTP 调用时更加安全。
      from requests.auth import HTTPDigestAuth 
response = reqs.get('https://postman-echo.com/digest-auth', auth=HTTPDigestAuth('postman', 
'password'))
    

摘要式身份验证仍然可能被黑客入侵,因此 HTTPs 或 SSL/TSL 安全性应该优于摘要式身份验证。

标头

标头包含有关客户端(浏览器类型)、服务器、接受的响应类型、IP 地址等的信息。标头可以根据源浏览器(用户代理)和内容类型进行自定义。可以使用headers属性查看它们,如下所示:

      headers = {'user-agent': 'customize header string', 'Content-Type': 'application/json; charset=utf-8'}  
response = requests.get(url, headers=headers)   # modify request headers 
print(response.headers)                         # print response headers 
print(response.headers['Content-Type'])         # output: application/json; charset=utf-8
    

曲奇饼

Cookie 是存储在客户端(浏览器)的一小段数据,通常用于维护登录会话或存储用户 ID。客户端和服务器都可以发送 Cookie。使用cookies属性可以发送和访问 Cookie。

      cookie = {'username':'Pavneet'} 
response = reqs.get('https://postman-echo.com/cookies/set',cookies = cookie)   # send cookie 
print(response.text)    # output: {"cookies":{"username":"Pavneet"}}
    

使用response.cookies访问服务器响应中的 cookie

超时和重定向

  • 超时:如果在设置的超时时间内没有响应,则允许请求终止任何请求。这将避免在服务器没有响应的情况下无限期等待的状态。
      requests.get('https://github.com/', timeout=0.50)
    
  • 重定向:请求提供url属性来跟踪重定向的 URL。
      response = requests.get('http://github.com/', allow_redirects=True) 
response.url
    
以上内容来自杭州电子商务研究院推送
分享到:

长按或扫码识别 分享给好友

长按或扫码识别 分享给好友
关于我们
热门推荐
合作伙伴
免责声明:本站部分资讯来源于网络,如有侵权请及时联系客服,我们将尽快处理
Copyright © 2025-2027 ToB产业网址导航 公安备案 浙公网安备33010602013138号 浙ICP备16025413号-9
支持 反馈 关注 数据