导入模块
import requests
发生请求
模式一
r = requests.get("https://xxxx.com/app/version") # GET请求
r = requests.post("https://xxxx.com/app/version") # POST请求
r = requests.put("https://xxxx.com/app/version") # PUT请求
r = requests.delete("https://xxxx.com/app/version") # DELETE请求
r = requests.head("https://xxxx.com/app/version") # HEAD请求
r = requests.options("https://xxxx.com/app/version") # OPTIONS请求
模式二
url="https://xxxx.com/app/version"
params = {"name": "xiaoMing", "age": 23}
cookies = {'key': 'value'}
header = {'user-agent': 'my-app/0.0.1''}
r = requests.get(url=url, params=params, cookies=cookies, headers=header, timeout=10) # GET请求
r = requests.post(url=url, params=params, cookies=cookies, headers=header, timeout=10) # POST请求
r = requests.put(url=url, params=params, cookies=cookies, headers=header, timeout=10) # PUT请求
r = requests.delete(url=url, params=params, cookies=cookies, headers=header, timeout=10) # DELETE请求
r = requests.head(url=url, params=params, cookies=cookies, headers=header, timeout=10) # HEAD请求
r = requests.options(url=url, params=params, cookies=cookies, headers=header, timeout=10) # OPTIONS请求
响应内容
r.encoding #获取当前的编码
r.encoding = 'utf-8' #设置编码
r.text #以encoding解析返回内容。字符串方式的响应体,会自动根据响应头部的 encoding 字符编码进行解码。
r.content #以字节形式(二进制)返回。字节方式的响应体
r.json() #以json形式返回,前提返回的内容确保是json格式的,不然解析出错会抛异常
r.headers #以字典对象存储服务器响应头,但是这个字典比较特殊,字典键不区分大小写,若键不存在则返回None
r.status_code #响应状态码、
r.raise_for_status() # 如果响应状态码不是 200,就主动抛出异常
r.headers #返回字典类型,头信息
r.requests.headers #返回发送到服务器的头信息
r.cookies #返回cookie
r.history #返回重定向信息,当然可以在请求是加上allow_redirects = false 阻止重定向
样例:get
r = requests.get("https://xxxx.com/app/version")
添加参数
params = {"name": "xiaoMing", "age": 23}
r = requests.get(url="https://api-local.chiyue365.com/v8/app/version", params=params)
添加 cookies
params = {"name": "xiaoMing", "age": 23}
cookies = {'key': 'value'}
r = requests.get(url="https://api-local.chiyue365.com/v8/app/version", params=params, cookies=cookies)
添加超时
r = requests.get(url="https://api-local.chiyue365.com/v8/app/version", timeout=10)
样例:获取手机号信息
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import requests
def main():
try:
url = " http://tcc.taobao.com/cc/json/mobile_tel_segment.htm?tel=15911111111"
r = requests.get(url)
r.raise_for_status()
r.encoding = r.apparent_encoding
result = r.text
print(result)
except Exception as err:
print(err)
return None
if __name__ == "__main__":
main()
执行结果
request间数据传输-设置session
import requests
def before():
s = requests.sessions
s.name = "小明"
def main():
before()
s = requests.sessions
print(s.name)
执行结果
上传图片
import requests
url = 'https://xxxx.com/upload'
files = {'file': open('/test.jpg', 'rb')}
r = requests.post(url, files=files)
print(r.text)