Python之requests模块获取与使用cookie的方法
一. 处理cookie 1. 处理cookie方法一:用requests.utils.dict_from_cookiejar() 把返回的cookies转换成字典 1 import requests 23 def login(): 4url = 'http://www.xxx.com/login 5headers = { 6'Content-Type': "application/json"
·
一. 处理cookie
- 方法一:用
requests.utils.dict_from_cookiejar()
把返回的cookies转换成字典
import requests
def login():
url = 'http://www.xxx.com/login'
headers = {
'Content-Type': "application/json"
}
payload = {
"usercode": "111@qq.com",
"password": "11111"
}
try:
res = requests.post(url, headers=headers, json=payload)
cookies = res.cookies
cookie = requests.utils.dict_from_cookiejar(cookies)
return cookie
except Exception as err:
print('获取cookie失败:\n{0}'.format(err))
- 方法二:遍历cookies的键值,拼接成cookie格式
import requests
def login():
login_url = 'http://www.baidu.com/login'
headers = {
'Content-Type': "application/json"
}
payload = {
"usercode": "11111@qq.com",
"password": "1111"
}
try:
res = requests.post(url=login_url, headers=headers, json= payload)
cookies = res.cookies.items()
cookie = ''
for name, value in cookies:
cookie += '{0}={1};'.format(name, value)
return cookie
except Exception as err:
print('获取cookie失败:\n{0}'.format(err))
二. 使用cookie
- 方法一:
import requests
def get_data():
cookie = login()
res = requests.get(url=get_url, cookies=cookie)
print(res.text)
- 方法二:
import requests
def get_data():
cookie = login()
headers = {"cookie": cookie}
res = requests.get(url=get_url, headers=headers)
print(res.text)
转载:https://www.cnblogs.com/shukeshu/p/14747736.html
更多推荐
已为社区贡献4条内容
所有评论(0)