基本操作
1.各种请求方式
get、post、put、delete、head、options
网址:http://httpbin.org/get
2.响应请求
response = requests.get("www.baidu.com") 请求百度信息
print(response.status_code) 状态码
print(response.text) 响应内容
print(response.cookies) 登录信息
3.带参数的请求
response = requests.get("http://www.baidu.com/get?name=joy&age=22")
这种写法较为繁琐,可改为使用字典。
4.使用参数字典的请求
data = {'name':'joy',
'age':'19'}
response = requests.get("www.baidu.com", params=data)
print(response.text)
5.获取解析json数据
import requests 导包
import json
response = requests.get("www.baidu.com")
print(response.json) 效果等同于 print(json.load(response.text))
这样就可以使用字典来取出你需要的数据
6.获取二进制数据
response = requests.get("www.baidu.com")
print(response.content)
7.保存数据
response = requests.get("www.baidu.com")
with open('localtion.html','wb') as f: b表示二进制数据
f.write(response.content)
f.close
8.添加headers伪装
heades = {}
模拟谷歌:进入浏览器,右键点击检查,进入Network,然后进入Headers,复制其信息
response =requests.get("www.baidu.com", headers=headers)
print(response.status_code) 状态码200为正常
9.状态码判断
response = requests.get("www.baidu.com")
exit() if not response.status_code == 200 else print("Request Successfuily")
高级操作
1.文件上传
files = {'file': open('图片二进制信息', 'rb')}
response = requests.post('http://httpbin.org/post',files=files)
print(response.content)
2.回话维持
s = requests.Session()
s.get("http://httpbin.org/cookies/number/123123")
response = s.get("http://httpbin.org/cookies")
print(response.text)
可以得到:
{"cookies": {"number": "123123"}}
3.获取cookies
response = requests.get("www.baidu.com")
for k,v in response.cookies.items():
print(k + "=" + v)
4.设置代理
proxies = {
"http": "http://127.0.0.1:3306",
"http": "http://user:password@127.0.0.1:3306"
}
response = requests.get("www.baidu.com", proxies=proxies)
print(response.status_code)
5.超时设置
response = requests.get("www.baidu.com", timeout=1)
print(response.status_code)
6.认证设置
response = requests.get("www.baidu.com", auth=('root','123456'))
print(response.status_code)
7.异常处理
import requests
from requests.exception import ReadTimeout,ConnectionError,RequestException
try:
response = requests.get("www.baidu.com", timeout=1)
print(response.status_code)
except ReadTimeout:
print("超时")
except ConnectionError:
print("网络错误")
except RequestException:
print("出错")
先捕获子类异常,再捕获父类异常,可清晰分析错误地方