Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selenium: Why my get_cookies() method returned a list in Python?

Below is my script:

# -*- coding: UTF-8 -*-
from selenium import webdriver

driver = webdriver.Firefox()

driver.get("http://www.google.com")

all_cookies = driver.get_cookies()

print all_cookies

and the print result is:

>>> 
[{u'domain': u'.google.com.hk', u'name': u'PREF', u'value': u'ID=999c3b8cf82fb5bc:U=7d4d0968915e2147:FF=2:LD=zh-CN:NW=1:TM=1341066316:LM=1341066316:S=kDqT8587qbZJj1_B', u'expiry': 1404138316, u'path': u'/', u'secure': False}, {u'domain': u'.google.com.hk', u'name': u'NID', u'value': u'61=AbRSUZokdEP3hN79nLdNOWwlF7itUX9-pmFAIBb-ysJqvoi1NBsmOa2wV7ldWgXpYBd_OsPnMxaAPiRsJyCpVbCN882MWNn6DwNm9eD6PTKU2gfDfqrj2EJr6CNVUhI6', u'expiry': 1356877516, u'path': u'/', u'secure': False}]
>>> 

The return is a list, but it should be a dictionary.

like image 391
Rio_Ma Avatar asked Jun 30 '12 14:06

Rio_Ma


1 Answers

Cookies contain a lot more information than simply name and value information, for example expiration date, domain, etc. Therefore, a simple key/value pair is not sufficient. If all you're interested in ONLY the name and its corresponding value, then I'd do something similar to the following to construct your own dictionary:

# -*- coding: UTF-8 -*-
from selenium import webdriver

driver = webdriver.Firefox()
driver.get("http://www.google.com")
cookies_list = driver.get_cookies()
cookies_dict = {}
for cookie in cookies_list:
    cookies_dict[cookie['name']] = cookie['value']

print(cookies_dict)
like image 124
Joshua Burns Avatar answered Oct 17 '22 02:10

Joshua Burns