当前位置: 首页> 教育> 锐评 > 苏州有什么好玩的景点_前端工程师考证报名_河南做网站优化_google 谷歌

苏州有什么好玩的景点_前端工程师考证报名_河南做网站优化_google 谷歌

时间:2025/8/25 11:14:20来源:https://blog.csdn.net/a876106354/article/details/144338432 浏览次数:0次
苏州有什么好玩的景点_前端工程师考证报名_河南做网站优化_google 谷歌

一、‌Requests的介绍

        Requests 是一个简单易用的 HTTP 库,用于发送各种 HTTP 请求。它由 Kenneth Reitz 创建,并广泛用于 Python 社区中。

二、‌Requests的特点

1、人性化的 API:简洁的接口使得编写请求代码变得简单直观。

2、跨平台:在 Windows、OS X、Linux 等多种操作系统上都可以使用。

3、只包含核心功能:专注于提供基本的 HTTP 请求功能,易于扩展。

4、自动处理 Cookies:自动处理客户端的 Cookies。

5、自动处理重定向:遵循 HTTP 重定向。

6、SSL 验证:支持 HTTPS 请求,并默认验证 SSL 证书。

三、Requests的安装使用

安装 Requests 库

Requests 库不是 Python 的标准库,因此需要单独安装。可以通过 pip 安装:

pip install requests

使用 Requests 库

以下是使用 Requests 库发送 HTTP 请求的基本步骤:

1. 发送 GET 请求
import requests# 发送 GET 请求
response = requests.get('https://api.github.com')# 获取响应内容
data = response.text# 打印响应内容
print(data)

2. 发送 POST 请求

import requests# 发送 POST 请求
response = requests.post('https://httpbin.org/post', data={'key': 'value'})# 获取响应内容
data = response.json()  # 响应内容为 JSON 格式# 打印响应内容
print(data)

3. 处理响应

Requests 库提供了多种方法来处理响应:

  • response.text:返回响应内容作为 Unicode 字符串。
  • response.content:返回响应内容作为字节序列。
  • response.json():将响应内容解析为 JSON 格式。
# 假设响应内容为 JSON 格式
data = response.json()
print(data)

4. 发送带有 Headers 的请求

import requestsheaders = {'User-Agent': 'my-app/0.0.1','Accept': 'application/json',
}response = requests.get('https://api.github.com', headers=headers)

5. 发送带有认证信息的请求
import requestsusername = 'user'
password = 'pass'response = requests.get('https://api.github.com', auth=(username, password))

6. 发送带有超时的请求
import requeststry:response = requests.get('https://api.github.com', timeout=0.01)
except requests.exceptions.Timeout:print("请求超时")

四、Requests的详细使用

以下是一些 Python Requests 库的高级示例代码,这些示例展示了如何使用 Requests 库进行更复杂的操作,如会话管理、文件上传、代理设置、异常处理等。

1. 会话管理

使用会话(Session)可以在多个请求之间保持某些参数,比如 cookies。

import requests# 创建一个会话对象
with requests.Session() as session:session.headers.update({'x-requested-with': 'XMLHttpRequest'})response = session.get('https://api.example.com/data')print(response.text)

2. 文件上传

使用 Requests 上传文件。

import requestsurl = 'https://httpbin.org/post'
files = {'file': open('example.txt', 'rb')}response = requests.post(url, files=files)print(response.text)

3. 代理设置

通过代理发送请求。

import requestsproxies = {'http': 'http://10.10.1.10:3128','https': 'http://10.10.1.10:1080',
}response = requests.get('https://api.example.com/data', proxies=proxies)
print(response.text)

4. 异常处理

处理请求过程中可能出现的异常。

import requests
from requests.exceptions import HTTPErrorurl = 'https://api.example.com/data'try:response = requests.get(url)response.raise_for_status()  # 将捕获HTTP错误
except HTTPError as http_err:print(f'HTTP error occurred: {http_err}')
except Exception as err:print(f'Other error occurred: {err}')
else:print(response.text)

5. JSON 数据请求

发送 JSON 数据并解析响应的 JSON。

import requests
import jsonurl = 'https://httpbin.org/post'
payload = {'key1': 'value1', 'key2': 'value2'}response = requests.post(url, data=json.dumps(payload), headers={'Content-Type': 'application/json'})
data = response.json()print(data)

6. 流式请求

用于处理大量数据的流式请求。

import requestsurl = 'https://files.pythonhosted.org/packages/source/r/requests/requests-2.25.1.tar.gz'
response = requests.get(url, stream=True)with open('requests-2.25.1.tar.gz', 'wb') as file:for chunk in response.iter_content(chunk_size=1024):file.write(chunk)

7. 自定义认证

使用自定义认证方式,例如基本认证。

import requests
from requests.auth import HTTPBasicAuthurl = 'https://api.example.com/data'
response = requests.get(url, auth=HTTPBasicAuth('username', 'password'))print(response.text)

8. 使用 SSL 证书

当需要验证 SSL 证书时,可以指定证书路径。

import requestsurl = 'https://api.example.com/data'
response = requests.get(url, cert='/path/to/certfile')print(response.text)

五、注意事项

  • Requests 库默认不发送 Accept 头部,如果你需要处理 JSON 数据,可能需要手动设置。
  • 出于安全考虑,默认情况下 Requests 会验证 SSL 证书。如果需要跳过 SSL 验证(不推荐),可以设置 verify=False

关键字:苏州有什么好玩的景点_前端工程师考证报名_河南做网站优化_google 谷歌

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: