Python requests 依赖库

本文最后更新于:2021年5月21日晚上6点49分

导入模块

1
import requests

建立会话

1
2
import requests
r = requests.session()

Get 请求

1
2
3
import requests
params = {"id" : "1234"}
r = requests.get('https://www.xiinnn.com/', params = params)

Post 请求

1
2
3
import requests
payload = {'key':'value'}
r = requests.post('https://www.xiinnn.com/',data = payload )

传递URL参数

1
2
3
4
import requests
payload = {'p':595}
r = requests.get("http://www.xiinnn.com/")
等价于r = requests.get("http://www.xiinnn/com?p=595/")

获取请求头部信息

1
2
3
4
5
import requests
r = requests.get('https://www.xiinnn.com/')
print(r.request.headers)
#输出结果:
#{'User-Agent': 'python-requests/2.19.1', 'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'Connection': 'keep-alive'}

响应——编码格式

1
2
3
4
import requests
r = requests.get('https://www.xiinnn.com/')
print(r.encoding) #打印输出默认的编码格式
r.encoding = 'UTF-8' #修改编码格式

响应——获取头部信息

获取响应中所有头部信息

1
2
3
4
5
6
7
import requests
r = requests.get('https://www.xiinnn.com/')
print(r.headers)
'''
输出结果如下
{'Date': 'Mon, 22 Feb 2021 12:16:56 GMT', 'Server': 'Apache', 'Link': '<https://www.xiinnn.com/wp-json/>; rel="https://api.w.org/"', 'Upgrade': 'h2', 'Connection': 'Upgrade, close', 'Vary': 'Accept-Encoding', 'Content-Encoding': 'gzip', 'Content-Length': '4500', 'Content-Type': 'text/html; charset=UTF-8'}
'''

获取响应中特定的信息

1
2
3
4
5
import requests
r = requests.get('https://www.xiinnn.com/')
print(r.headers['Content-Length'])
#输出结果:
#4500

响应——状态码

输出状态码

1
2
3
4
5
import requests
r = requests.get('https://www.xiinnn.com/')
print(r.status_code)
#输出结果:
#200

内置状态码对象(requests.codes.ok)

1
2
3
4
5
import requests
r = requests.get('https://www.xiinnn.com/')
print(r.status_code == requests.codes.ok)
#输出结果:
#True

超时:

1
2
3
import requests
r = requests.get('https://www.xiinnn.com/',timeout = 0.5)
#设置超时时间0.5s

快速访问请求头中的Cookie

1
2
3
import requests
r = requests.get('https://www.xiinnn.com/')
print(r.cookies)

自行设置cookie

1
2
3
import requests
cookies = {'key','value'}
r = requests.get('https://www.xiinnn.com',cookies = cookies)

本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!