# session使用
import requests
s = requests.Session()
'''
#sesseion使用
# 直接访问不返回cookies
r = s.get("http://httpbin.org/cookies")
print(r.text)
# 第一步:发送一个请求,用于设置请求中的cookies
# http://httpbin.org能够用于测试http请求和响应
s.get('http://httpbin.org/cookies/set/sessioncookie/123456789')
# 第二步:再发送一个请求,用于查看当前请求中的cookies
r = s.get("http://httpbin.org/cookies")
print(r.text)
'''
'''
# header使用
r = s.get('http://httpbin.org/headers')
print(r.text) # 返回正常headers
s.headers.update({'x-test': 'true'})
r1 = s.get('http://httpbin.org/headers', headers={'x-test2': 'true'})
print(r1.text) # 返回headers 包含x-test和x-text2字段
r2 = s.get('http://httpbin.org/headers')
print(r2.text) # 返回headers 包含x-test字段
'''
# cookies获取与使用
# 1.获取本地cookies
# 2.使用Selenium获取cookies:https://www.cnblogs.com/573734817pc/p/11176815.html
# 3.常规获取,如下
import requests
'''
# 登录获取cookies
res = requests.post(url='login_url')
cookies = res.cookies
cookie = requests.utils.dict_from_cookiejar(cookies)
# 使用cookies
res = requests.get(url='get_data_url', cookies=cookie)
print(res.text)
'''
'''
# 登录获取cookies
res = requests.post(url='login_url')
cookies = res.cookies.items()
cookie = ''
for name, value in cookies:
cookie += '{0}={1};'.format(name, value)
# 使用cookies
headers = {
"cookie": cookie
}
res = requests.get(url='get_data_url', headers=headers)
'''
'''
#两种混合(不建议)
res = requests.post(url='login_url')
cookies = res.cookies
phpsessid = cookies['phpsessid']
env_orgcode = cookies['env_orgcode']
acw_tc = cookies['acw_tc']
aliyungf_tc = cookies['aliyungf_tc']
last_env = cookies['last_env']
cookie = 'phpsessid={0};env_orgcode={1};acw_tc{2};aliyungf_tc={3};last_env={4}'.format(
phpsessid, env_orgcode, acw_tc, aliyungf_tc, last_env
)
headers = {
"cookie": cookie
}
res = requests.get(url='get_data_url', headers=headers)
'''
原理:https://blog.youkuaiyun.com/zwq912318834/article/details/79930423
# data都是字典格式
Post表单请求: Form Data代码示例
headers = {
"Content-Type": "application/x-www-form-urlencoded"
}
requests.post(url, data=data, headers=headers)
#requests.post(url, json=data, headers=headers)
Post表单请求: Request Payload代码示例
headers = {
"Content-Type": "application/json"
}
requests.post(url, data=json.dumps(data), headers=headers)