Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I load session and cookies from Selenium browser to requests library in Python?

How can I load session and cookies from Selenium browser? The following code:

import requests  cookies = [{u'domain': u'academics.vit.ac.in',             u'name': u'ASPSESSIONIDAEQDTQRB',             u'value': u'ADGIJGJDDGLFIIOCEZJHJCGC',             u'expiry': None, u'path': u'/',             u'secure': True}] response = requests.get(url2, cookies=cookies) 

gives me the following exception:

Traceback (most recent call last):   File "F:\PYTHON\python_scripts\cookies\cookies3.py", line 23, in <module>     response = requests.get(url2, cookies=cookies)   File "C:\Python27\lib\site-packages\requests\api.py", line 68, in get     return request('get', url, **kwargs)<br/>   File "C:\Python27\lib\site-packages\requests\sessions.py", line 450, in request     prep = self.prepare_request(req)     cookies = cookiejar_from_dict(cookies)   File "C:\Python27\lib\site-packages\requests\cookies.py", line 439, in cookiejar_from_dict     cookiejar.set_cookie(create_cookie(name, cookie_dict[name])) TypeError: list indices must be integers, not dict 
like image 690
cibin Avatar asked Apr 10 '15 13:04

cibin


People also ask

Can you use Selenium and requests together?

Extends Selenium WebDriver classes to include the request function from the Requests library, while doing all the needed cookie and request headers handling.


1 Answers

First you have to get the cookies from your driver instance:

cookies = driver.get_cookies() 

This returns cookie dictionaries for your session.

Next, set those cookies in requests:

s = requests.Session() for cookie in cookies:     s.cookies.set(cookie['name'], cookie['value']) 
like image 181
That1Guy Avatar answered Sep 16 '22 13:09

That1Guy