一、requests库
requests库文档地址:https://2.python-requests.org//zh_CN/latest/user/quickstart.html
带参数的get请求
response = requests.get(url, params=data).其中data为字典类型。不需要url额外的转码。
返回结果
- response.text。类型为str
- response.json().返回结果为json对象,与json.loads(response.text)相同。常用于ajax请求。
response.conten获取二进制内容。类型为bytes。 - 添加headers。headers={}
post请求
requests.post(data=data, headers=headers)
响应
response.status_code
response.headers
response.cookies
response.url
回话维持(模拟登陆)
s = requests.Session()
s.get()
证书验证
response = requests(url, verify=False)
运行会产生警告,
消除警告:
from requests.packages import urllib3
urllib3.disable_warnings()
代理设置
proxies = {
"http": "http://123.",
"https": "https://146."
"http": "http://user:password@123."
}
requests.get(url, proxies=proxies)
链接超时
response = requests.get(url, timeout=1)
指定时间内不能访问,抛出异常。
try:
捕获异常
except:
认证设置
异常处理
from request.exception import ReadTimout, HTTPError
try:
response = requests.get(url, timeout=1)
except ReadTimeException:
print("Error")