Python-requests库入门指南

介绍

Python编写的HTTP库,能够发送HTTP和HTTPS请求,并且获取响应。在测试服务器响应方面经常使用。

下载

pip install requests

使用

常用的格式

  • requests.get(url, params=None, **kwargs)
  • requests.post(url, data=None, json=None, **kwargs)

参数介绍 

Requests库中的参数可以分为两个阶段:发起请求时的参数和获取响应后的参数。下面我们来详细看看这两个阶段的参数。

发起请求时的参数

  • method:请求方法,常用的有 GET、POST、PUT、HEAD、OPTIONS、PATCH 等。
  • url:请求地址,即你想要访问的目标 URL。
  • data:请求 BADY,可选参数,用于在请求中传递数据。它可以接受不同类型的数据,包括字符串、字典和文件。
  • params:查询参数,可选参数,用于指定请求中的查询参数。这允许你在 URL 中附加额外的参数以进行请求。
  • json:JSON 数据,可选参数,用于指定要发送的 JSON 数据。系统会自动将字典转化为 JSON 数据。
  • files:上传文件,可选参数,用于文件上传。你可以传递文件对象以上传到服务器。
  • proxies:设置代理,可选参数,允许你通过代理服务器发送请求,以访问受限制的资源。
  • headers:请求头,可选参数,用于自定义设置 HTTP 请求头信息。
  • cookies:Cookie,可选参数,用于发送 HTTP 请求时传递的 Cookie 信息。通常用于模拟已登录状态。
  • allow_redirects:是否允许重定向,默认为 True。
  • verify:是否验证 HTTPS 证书,默认为 True。
  • timeout:设置请求超时时间,以秒为单位。

以下是一个示例,展示了如何使用这些参数发起GET请求:

# 导入requests包
import requests
# 自定义请求头
headers = {"Content-Type": "application/x-www-form-urlencoded"}
# 添加cookie
cookies = {'session_id': 'abcdef12345'}
# 添加请求BADY
data = "username=admin&password=123456&verifycode=0123"
# 添加代理
proxies = {    
    'http':'http://127.0.0.1:8888', 
    'https':'http://127.0.0.1:8888'
}
# 发送post请求
response = requests.get('https://www.baidu.com',data = data,headers = headers,cookies = cookies,proxies = proxies)

获取响应时的参数

  • status_code:响应状态码。
  • headers:响应的请求头信息。
  • request.headers:发送HTTP请求时的请求头部信息
  • encoding:响应的编码格式。
  • content:响应体,字节类型,包含原始的二进制信息。
  • text:响应体,字符串类型,会自动根据 HTTP 头部的编码信息返回内容。
  • cookies:响应对应请求的 Cookie 信息,是一个 RequestsCookieJar 对象。

注:headers 和 request.headers 是不同的请求头信息,前者是响应的请求头,后者是对于请求所响应

以下是一个示例,展示了如何使用这些参数获取响应的信息:

# 导入requests包
>>> import requests

# 发送get请求
>>> response = requests.get('https://www.baidu.com/s?wd=上海')

# 获取响应的状态码
>>> status_code = response.status_code
200

# 获取响应的响应头
>>> headers = response.headers
{'Accept-Ranges': 'bytes', 'Cache-Control': 'no-cache', 'Connection': 'keep-alive', 'Content-Length': '227', 'Content-Security-Policy': "frame-ancestors 'self' https://chat.baidu.com http://mirror-chat.baidu.com https://fj-chat.baidu.com https://hba-chat.baidu.com https://hbe-chat.baidu.com https://njjs-chat.baidu.com https://nj-chat.baidu.com https://hna-chat.baidu.com https://hnb-chat.baidu.com http://debug.baidu-int.com;", 'Content-Type': 'text/html', 'Date': 'Tue, 19 Sep 2023 04:48:23 GMT', 'P3p': 'CP=" OTI DSP COR IVA OUR IND COM ", CP=" OTI DSP COR IVA OUR IND COM "', 'Pragma': 'no-cache', 'Server': 'BWS/1.1', 'Set-Cookie': 'BD_NOT_HTTPS=1; path=/; Max-Age=300, BIDUPSID=C6D797F5E9E2D3B9FFE04CE0338CC619; expires=Thu, 31-Dec-37 23:55:55 GMT; max-age=2147483647; path=/; domain=.baidu.com, PSTM=1695098903; expires=Thu, 31-Dec-37 23:55:55 GMT; max-age=2147483647; path=/; domain=.baidu.com, BAIDUID=C6D797F5E9E2D3B904C8EFA4EBC80FD9:FG=1; max-age=31536000; expires=Wed, 18-Sep-24 04:48:23 GMT; domain=.baidu.com; path=/; version=1; comment=bd', 'Traceid': '1695098903054653569015203487008619068969', 'X-Ua-Compatible': 'IE=Edge,chrome=1'}

# 获取响应对应请求的请求头
>>> header = response.request.headers
{'User-Agent': 'python-requests/2.31.0', 'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'Connection': 'keep-alive'}

# 获取响应的编码格式
>>> encoding = response.encoding
ISO-8859-1

# 获取响应的二进制信息(响应体)
>>> content = response.content
b'<html>\r\n<head>\r\n\t<script>\r\n\t\tlocation.replace(location.href.replace("https://","http://"));\r\n\t</script>\r\n</head>\r\n<body>\r\n\t<noscript><meta http-equiv="refresh" content="0;url=http://www.baidu.com/"></noscript>\r\n</body>\r\n</html>'

# 获取响应的文本内容
>>> text = response.text
<html><head><script>location.replace(location.href.replace("https://","http://"));</script></head><body><noscript><meta http-equiv="refresh" content="0;url=http://www.baidu.com/"></noscript></body></html>

# 获取响应的cookie
>>> cookie = response.cookies
<RequestsCookieJar[<Cookie BD_NOT_HTTPS=1 for www.baidu.com/>, <Cookie BIDUPSID=7289C01F27BE4D6DC74074AF58FBE32D for .baidu.com/>, <Cookie PSTM=1695099613 for .baidu.com/>, <Cookie BAIDUID=7289C01F27BE4D6D9F92405805C4BD8D:FG=1 for .baidu.com/>]>

常用使用方式

会话管理

import requests

session = requests.Session()
session.get('https://www.baidu.com/login', params={'user': 'username', 'pass': 'password'})
response = session.get('https://www.baidu.com/dashboard')

文件上传

import requests

files = {'file': open('文件名+后缀', 'rb')}
response = requests.post('https://example.com/upload', files=files)

代理设置

import requests

proxies = {'http': 'http://proxy.example.com', 'https': 'https://proxy.example.com'}
response = requests.get('https://example.com', proxies=proxies)

使用get获取图片

import requests
resp = requests.get('https://pic2.zhimg.com/v2-dad4bf18cb546d9c52ade85d4fba6225_r.jpg')
# Response对象.content: 返回响应的二进制字节串
print(resp.content)
with open('宋茜.jpg', 'wb') as f:
	f.write(resp.content)

请求验证

import requests
# verify默认为True,意思是需要做证书校验
# 如果不希望检查证书,可以将verify设置为False,否则需要指定cert关键字,给出证书的路径
# 针对HTTPS请求做证书校验
resp = requests.get('https://www.woniuxy.com/', verify=True, cert='C://tls.pem')
# 不做证书校验
resp2 = requests.get('https://www.woniuxy.com/', verify=False)
print(resp.status_code)
print(resp.text)
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

牧魂.

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值