Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 849
robert Avatar asked Dec 24 '22 03:12

robert


1 Answers

all_cookies=self.driver.get_cookies();
cookies_dict = {}
for cookie in all_cookies:
    cookies_dict[cookie['name']] = cookie['value']
print(cookies_dict)

You can pass these to requests functions.

like image 123
Libin Thomas Avatar answered May 20 '23 03:05

Libin Thomas