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

后端 未结 3 609
礼貌的吻别
礼貌的吻别 2021-02-04 10:10

Below is my script:

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

driver = webdriver.Firefox()

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

all_cookies = dr         


        
相关标签:
3条回答
  • 2021-02-04 10:32

    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)
    
    0 讨论(0)
  • 2021-02-04 10:35

    I understand that get_cookies() returns a list of dictionaries, each dict holding the properties for each cookie found:

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

    0 讨论(0)
  • 2021-02-04 10:52

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

    i.e.

    driver.get_cookies() #returns list of cookie dictionaries
    driver.get_cookie(name) # returns a cookie dictionary of specified cookie
    
    0 讨论(0)
提交回复
热议问题