请求中添加cookies
对于某些网站,登录然后从浏览器中获取cookies,以后就可以直接拿着cookie登录了,无需输入用户 名密码。
一、在参数中添加cookie
在发送请求时使用cookies
代码示例:
import requests # 1,在参数中添加 cookie_dict = {"login_name":"admin"} # cookie做一个变量,然后再请求中使用cookies response = requests.get(url="http://www.hnxmxit.com",cookies=cookie_dict)
查看执行结果:
二、在头部添加cookie
在发送请求时使用headers
代码示例:
# 2,在头部添加 cookie_header = {"login_name":"root"} res = requests.get(url="http://www.hnxmxit.com",headers=cookie_header)
查看执行结果
通过session添加cookie
代码示例:
# session添加cookie import requests session_obj = requests.session() # 方法1: # session_obj.cookies["test_add_cookie"]="newdream2021" # response = session_obj.get(url="http://www.hnxmxit.com") # 方法2: 推荐使用 session_obj.cookies.set("test_add_cookie","newdream") response = session_obj.get(url="http://www.hnxmxit.com") # 方法3: # cookie_dict = {"test_add_cookie":"newdream2020"} # requests.utils.add_dict_to_cookiejar(session_obj.cookies,cookie_dict) # response = session_obj.get(url="http://www.hnxmxit.com") # 方法4: # cookie_obj = requests.cookies.RequestsCookieJar() # cookie_obj.set("test_add_cookie","newdream2022") # session_obj.cookies.update(cookie_obj) # response = session_obj.get(url="http://www.hnxmxit.com")
添加cookie绕过登录
代码示例:
# 添加cookie绕过登录phpwind论坛 import requests,re # 1.手动打开论坛获取登录后的cookie # 2.添加cookie session_obj = requests.session() session_obj.cookies.set(name="zFb_lastvisit",value="eU3LmIB4gCR2k5lCRVBNs9E5smt4igrFH7fXe82e4aXo%2FGbpZ0gclab4jb8%3D",domain="47.107.178.45",path="/") session_obj.cookies.set(name="zFb_winduser",value="481%091648725688%09%2Fphpwind%2Findex.php%3Fm%3Du%26a%3Dshowcredit",domain="47.107.178.45",path="/") # 访问首页 response = session_obj.get(url="http://47.107.178.45/phpwind/") print(response.content.decode("utf-8"))