基础格式
import requests
'''
Get 请求处理
requests.get(url, params=None, **kwargs)
params : 参数字典
'''
# params
data = {
'name':'xxx',
'header':"xxx",
'cookies':"xxx"
}
# 发送请求
response = requests.get(url,params=data)
if(response.status_code == 200):
# text返回的是str格式内容,所以可用正则表达式去匹配需要的内容
print(response.text)
# 解析返回的JSON格式内容为字典
print(response.json())
# 如果是二进制内容,保存只需要以二进制方式写入文件即可
print(response.content)
高级用法
# 文件上传
files = {"file":open("file_path")}
response = requests.post(url,files=files)
print(response.status_code)
# 解析cookies
for key,value in response.cookies.items():
print(key + "=" + value)
# 维持会话
# 目的是模拟多个get/post请求是出自于同一个模拟浏览器
# 创建会话对象
S = requests.Session()
# 第一次请求设置cookies
res = S.get(url,cookies = set_cookies)
# 第二次请求获取设置的cookies
res = S.get(url)
print(S.cookies())
# SSL证书验证
# 当出现SSLError问题时说明SSL证书有问题
# 只需要将verify=False就行
response = requests.get("https://www.12306.com",verify = False)
# 但是会出现建议添加证书的警告,将警告输入日志
import loggings
logging.captureWarnings(True)
# 也可以从本地添加证书
response = requets.get("https://www.12306.com",cert = cert_file_path)
# 设置代理
proxies = {
'https':'http: //10.10.1.10: 1080',
'http':'http://user:password@10.10.1 .10:3128/',
}
response = requests.get("https://www.12306.com",proxies=proxies)
# 超时设置
# timeout默认为None永久等待,time=1表示时间综合为1s.time=(0.2,0.8)表示连结0.2s,读取0.8s
#身份验证
r = requests.get('http://localhost:sooo', auth=HTTPBasicAuth ('username','password'))
# 也可直接写元祖,默认HTTPBasicAuth 类
规范化请求
# Prepared Request
from requests import Request
url = 'http://httpbin.org/post'
data = {
'name ': 'germey'
headers = {
'User-Agent ' : 'Mozilla/s.o (Macintosh; Intel MacOSX10_11_4) AppleWebKit/537.36 (KHTML, like Gecko)
Chrome/53 .0.2785.116 Safari/537 .36'
}
s = Session()
req = Request('POST', url, data=data, headers=headers)
prepped = s.prepare_request(req)
r = s.send(prepped)
# 所有的请求数据参数集合在s中,后面会方便于构建请求队列