模拟登陆京东并访问我的订单
第一个出现错误
# -*- coding: utf-8 -*- import requests url = 'https://passport.jd.com/uc/loginService' headers = {'User-Agent':'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36'} data = { 'loginname': 'XXXXXXX', 'nloginpwd': 'XXXXXXXX' } r = requests.post(url, data) print r.text url1 = 'https://order.jd.com/center/list.action' r1 = requests.get(url1) print r1.text
第二个正常
import requests url = 'https://passport.jd.com/uc/loginService' headers = {'User-Agent':'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36'} data = { 'loginname': 'XXXXXXX', 'nloginpwd': 'XXXXXXXX' } session = requests.Session() r = session.post(url, data) print r.text url1 = 'https://order.jd.com/center/list.action' r1 = session.get(url1) print r1.text
非常清晰体现出了session的用途.
requests库的session对象能够帮我们跨请求保持某些参数,也会在同一个session实例发出的所有请求之间保持cookies
print r.cookies.values() print r1.cookies.values() print r.cookies.keys() print r1.cookies.keys() print r.cookies.get_dict() print r1.cookies.get_dict()
示例
s = requests.session()
# req_param = '{"belongId": "300001312","userName": "alitestss003","password":"pxkj88","captcha":"pxpx","captchaKey":"59675w1v8kdbpxv"}'
# res = s.post('http://test.e.fanxiaojian.cn/metis-in-web/auth/login', json=json.loads(req_param))
# # res1 = s.get("http://test.e.fanxiaojian.cn/eos--web/analysis/briefing")
# print(res.cookies.values()) 获取登陆的所有session
参考文献:
http://docs.python-requests.org/zh_CN/latest/user/quickstart.html
https://www.jb51.net/article/141305.htm
https://www.cnblogs.com/lingxia/p/9074620.html