普通请求get
import requests
response = requests.get('www.baidu.com') 不带参数
带参数
urlpara = {
'wd':'iphone&ipad',
'rsv_spt':'1'
}
response = requests.get('https://www.baidu.com/s',params=urlpara)
response.text #请求结果
普通请求post
基本post请求
headers = {
'user-agent': 'my-app/0.0.1',
'auth-type': 'jwt-token'
}
r = requests.post("http://httpbin.org/post", headers=headers)带请求头
payload = {'key1': 'value1', 'key2': 'value2'}
r = requests.post("http://httpbin.org/post", data=payload) 带数据包
注意,很多人请求头嫌难打的去https://curlconverter.com/这个网站可以快速构建本机的请求头,按照情况使用
json数据请求
import requests,json
payload = {
"Overall":"良好",
"Progress":"30%",
"Problems":[
{
"No" : 1,
"desc": "问题1...."
},
{
"No" : 2,
"desc": "问题2...."
},
]
}
r = requests.post("http://httpbin.org/post", data=json.dumps(payload))
或者
r = requests.post("http://httpbin.org/post", json=payload)
content = r.json()
文件请求
files = {'file': open('report.xls', 'rb')}
response = requests.post('https://api.example.com/upload', files=files)
代理请求
import requests
proxies = {
'http': 'http://127.0.0.1:8888',
'https': 'http://127.0.0.1:8888',
}
response = requests.get('www.baidu.com', proxies=proxies)
print(response.text)
下载图片
import requests
file_path = os.path.join(file_dir, image_name)
#路径拼接 file_dir是你默认的存储路径自定义 image_name为保存的照片名字
img_request = requests.get(url)
with open(file_path, 'wb') as f:
f.write(img_request.content)
请求特殊情况
超时
response = requests.get('www.baidu.com', timeout=0.01)
获取请求状态响应码
response = requests.get('www.baidu.com')
response.status_code