Python Selenium: How to get cookies and format them to use in an http request

久未见 提交于 2021-01-29 02:50:49

问题


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)

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

Thank you sincerely for any help.


回答1:


Use json to dump the cookies into an iterable which you could format:

import json
cookies_list = list(json.dumps(get_cookies))



回答2:


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)


来源:https://stackoverflow.com/questions/53095611/python-selenium-how-to-get-cookies-and-format-them-to-use-in-an-http-request

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!