Python Selenium:如何获取cookie并设置其格式以在http请求中使用 [英] Python Selenium: How to get cookies and format them to use in an http request

查看:103
本文介绍了Python Selenium:如何获取cookie并设置其格式以在http请求中使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道从硒webdriver实例(chromedriver)中获取cookie并将其转换为可以作为http标头传递的cookie字符串的最佳方法.这是我尝试过的方法:获取硒提供的每个cookie的字典列表,然后手动添加等号和分号来格式化它,就像在Cookie头中一样.问题是:这不起作用,在我正在测试的站点上,它返回500内部服务器错误,我认为这是由a引起的.对请求的处理不当;以及b.错误的请求,特别是cookie部分.

I am wondering the best way to get the cookies from a selenium webdriver instance (chromedriver), and convert them into a cookie string that can be passed as an http header. Here is the way I have tried doing it: getting the list of a dictionary per cookie that selenium provides, then manually adding equal signs and semicolons to format it as it would be in the Cookie header. The problem is: this does not work, on the site I'm testing it returns 500 internal server error, which I assume is caused by a. a bad handling of the request, and b. a bad request, specifically the cookie part.

cookies_list = driver.get_cookies()
cookieString = ""
for cookie in cookies_list[:-1]:
    cookieString = cookieString + cookie["name"] + "="+cookie["value"]+"; "

cookieString = cookieString  + cookies_list[-1]["name"] + "="+ cookies_list[-1]["value"]

print(cookieString)

是否有更简便的方法可以做到这一点,和/或格式化无法使用的cookie字符串有什么问题.

Is there an easier method to do this and/or what is the problem with my formatting the cookie string that doesn't work.

衷心感谢您的帮助.

推荐答案

您可以使用pickle将当前cookie保存为python对象.例如:

You can save the current cookies as a python object using pickle. For example:

import pickle
import selenium.webdriver 

driver = selenium.webdriver.Firefox()
driver.get("http://www.google.com")
pickle.dump( driver.get_cookies() , open("cookies.pkl","wb"))

,然后再将其添加回去:

and later to add them back:

import pickle
import selenium.webdriver 

driver = selenium.webdriver.Firefox()
driver.get("http://www.google.com")
cookies = pickle.load(open("cookies.pkl", "rb"))
for cookie in cookies:
    driver.add_cookie(cookie)

这篇关于Python Selenium:如何获取cookie并设置其格式以在http请求中使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆