Selenium: Why did my get_cookies () method return 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 print result:

 >>> [{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}] >>> , u'value': u'61 = AbRSUZokdEP3hN79nLdNOWwlF7itUX9-pmFAIBb-ysJqvoi1NBsmOa2wV7ldWgXpYBd_OsPnMxaAPiRsJyCpVbCN882MWNn6DwNm9eD6PTKU2gfDfqrj2EJr6CNVUhI6 ', u'expiry': >>> [{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}] >>> 

Refund is a list, but it should be a dictionary.

+10
source share
3 answers

Cookies contain much more information than just a name and meaning, such as an expiration date, domain, etc. Therefore, a simple key / value pair is not enough. If you are all interested in ONLY the name and its corresponding meaning, I would do something similar to the following to build my 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) 
+16
source

I understand that get_cookies() returns a list of dictionaries , each of which contains properties for each cookie found:

http://selenium-python.readthedocs.io/navigating.html#cookies

+4
source

since you requested all cookies with driver.get_cookies() it returns a list of dictionaries with a pair (key, value) for each cookie saved. If instead you are interested in a specific cookie identified with the name name you can request for this particular cookie by name with driver.get_cookie(name) , which returns cookies if not found, None if not.

those.

 driver.get_cookies() #returns list of cookie dictionaries driver.get_cookie(name) # returns a cookie dictionary of specified cookie 
+2
source

Source: https://habr.com/ru/post/919393/


All Articles