安装
发送请求
发送 GET 请求
url = '<http://httpbin.org/get>'
resp = requests.get(url )
复制代码
发送 POST 请求
url = '<http://httpbin.org/post>'
resp = requests.post(url)
复制代码
指定请求方法
url = '<http://httpbin.org/post>'
resp = requests.request(method='post', url=url)
复制代码
传输参数
GET 和 POST 都可以传递 URL 参数
params = {"page": 3}
requests.get(url, params=params)
复制代码
POST 通过 multipart/form-data 传递参数,GET 请求不可以
data = {"username": "abc", "password": "123456"}
requests.post(url, data=data)
复制代码
POST 通过 json 传递参数,GET 请求不可以
data = {"username": "abc", "password": "123456"}
requests.post(url, json=data)
复制代码
获取响应
获取文本
获取 json
获取二进制数据
它们之间的关系
鉴权
session 鉴权
课堂派中就是使用这种方式,登录后获取用户信息不需要手工添加其他的参数了。
def login_with_session():
s = requests.Session()
login_url = 'https://v4.ketangpai.com/UserApi/login'
data = {
"email": "w3.com",
"password": "ad6",
"remember": "0"
}
s.post(login_url, data)
user_url = 'https://v4.ketangpai.com/UserApi/getUserInfo'
r = s.get(user_url)
print(r.text)
复制代码
也可以手工添加 cookie:
def login():
url = 'https://v4.ketangpai.com/UserApi/login'
data = {
"email": "wcom",
"password": "456",
"remember": "0"
}
r = requests.post(url, data)
sid = r.cookies.get('PHPSESSID')
url = '<https://v4.ketangpai.com/UserApi/getUserInfo>'
r = requests.get(url, cookies={'PHPSESSID': sid})
print(r.text)
复制代码
token
def login():
url = 'http:///login'
data = {
"mobile_phone": "18111112222",
"pwd": "12345678"
}
r = requests.post(url, json=data, headers=headers)
content = r.json()
member_id = content['data']['id']
token_type = content['data']['token_info']['token_type']
token = content['data']['token_info']['token']
url = f'<http:/{member_id}/info>'
r = requests.get(url, headers=headers)
print(r.text)
复制代码
扩展
我是九柄,公众号【 九柄 】,分享软件测试文章、面试、教程资料,欢迎来看看。
评论