requests库使用cookies登录
方法1–直接将cookies放在header中
Cookie = 'dmall-locale=zh_CN; dmall-zone=null; partner_login_type=scanCode; ticket=xx; __test_token_=xx; ' \
'tempid=C8EB25BECA8000028C97FDC41CA02F00; updateTime=1590373715342; inited=true; ' \
'first_session_time=1590373720681; session_id=xx; web_session_count=2; data_seq=3; UYBFEWAEE=xx; ' \
'login_no="MDA2MjE2NDlfMTU4OTc4NTUxMDY="'
headers = {
"Cookie": Cookie,
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.162 Safari/537.36"
}
url = 'http://testpop-ware.dmall.com/pop/ware/price/change'
data = {'skuId':'8b0b1cb5eaed4a728b5e98e98097ec3e','price':'0.02'}
r = requests.post(url, data=data, headers=headers)
方法2–使用requests.Session()
import requests
Cookie = 'dmall-locale=zh_CN; dmall-zone=null; partner_login_type=scanCode; ticket=xx; __test_token_=xx; ' \
'tempid=C8EB25BECA8000028C97FDC41CA02F00; updateTime=1590373715342; inited=true; ' \
'first_session_time=1590373720681; session_id=xx; web_session_count=2; data_seq=3; UYBFEWAEE=xx; ' \
'login_no="MDA2MjE2NDlfMTU4OTc4NTUxMDY="'
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.162 Safari/537.36"
}
url = 'http://testpop-ware.dmall.com/pop/ware/price/change'
data = {'skuId':'8b0b1cb5eaed4a728b5e98e98097ec3e','price':'0.02'}
r = requests.Session()
r.cookies['cookie'] = Cookie
res = r.post(url, data=data, headers=headers)
cookies拼接
网站的cookies内容中,部分是通过登录接口去获取,部分是浏览器生成,但有些网站仅携带登录接口返回的cookies无法登录,此时,需要去拼接浏览器生成的部分。
import requests
Cookies = 'dmall-locale=zh_CN; dmall-zone=null; partner_login_type=scanCode; ticket=xx; __test_token_=xx; tempid=xx; updateTime=1590373715342; inited=true; first_session_time=1590373720681; session_id=C8EB25C02420000269961E00105B1E54; web_session_count=2; data_seq=3; UYBFEWAEE=xx"'
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.162 Safari/537.36"}
url = 'http://xx.com/pop/ware/login'
data = {'username':'11111111111','pwd':'qweqeqsdsf'}
r = requests.Session()
res = r.post(url, data=data, headers=headers)
cookies = {}
new_cookies_value = ''
# 获取登录接口的cookies,并转为字符串
for key, value in r.cookies.items():
new_cookies_value += key + '=' + value
# 拼接cookies
cookies['cookie'] = Cookies + '; ' + new_cookies_value
# 转换为jar类型,也可用r.cookies['cookie'] = Cookie
cookies = requests.utils.cookiejar_from_dict(cookies, cookiejar=None, overwrite=True)
r.cookies = cookies