Selenium Chromedriver add cookie - invalid domain error

15,436

I was getting this error too in Py selenium.

The solution is: First visit the home page of the website whose cookies you are trying to add.

    # first visit home page
    url = "https://www.website.com"
    driver.get(url)

    # add cookies from pickled-txt or a txt file
    cookies = pickle.load(open("cookies.pkl", "rb"))
    for cookie in cookies:
        driver.add_cookie(cookie)

    # visit again and you shall see your account logged in
    url = "https://www.website.com"
    driver.get(url)

The reason is:

  1. Selenium webdriver init with default url data:.
  2. add_cookie require current url is under the domain pattern of cookie.
  3. data: will not match any cookie domain

So, you get invalid cookie domain error.

Share:
15,436
Admin
Author by

Admin

Updated on July 28, 2022

Comments

  • Admin
    Admin almost 2 years

    I am trying to store and upload a cookie that I retrieve from a webpage via selenium.

    I am new to cookies so please tell me what I am doing wrong. I am trying to learn.

    I open a page up with selenium, manually log in, peform some action then wait.. (and my code is set to get cookies after 30 seconds )

    print "adding cookies now"
    cookies = pickle.load(open("cookies.pkl", "rb"))
    for cookie in cookies:
        driver.add_cookie(cookie)
    

    after that, my cookies.pkl file looks something like this:

    (lp0
    (dp1
    Vdomain
    p2
    V.twitter.com
    p3
    sVsecure
    p4
    I00
    sVvalue
    p5
    V"v3:1484006785862560132892059"
    p6
    sVexpiry
    p7
    F1531267585.126113
    sVpath
    p8
    # more lines
    

    after this log_in_and_store(), i try to reopen the page with selenium while loading this cookies. If done correctly, it should open to the page i left off! Not the login page.

    When I try uploading my cookies to the webpage like this:

    driver.get('http://www.website.com')
    cookies = pickle.load(open("cookies.pkl", "rb"))
    for cookie in cookies:
        print cookie
        driver.add_cookie(cookie)
    

    add_cookies are throwing this error:

    selenium.common.exceptions.WebDriverException: Message: invalid cookie domain: invalid domain:".twitter.com" (Session info: chrome=55.0.2883.95) (Driver info: chromedriver=2.24.417412 (ac882d3ce7c0d99292439bf3405780058fcca0a6),platform=Mac OS X 10.12.1 x86_64)

    I tried this already, SO PLEASE DONT LINK ME TO IT(Selenium addCookie getting Invalid Cookie Domain Exception even though I'm on the right domain)

    Ive also tried changing chromedriver versions, changing my code a million times and banging my head against the wall. none of those worked.

    Please help, thank you very much

  • grantr
    grantr about 2 years
    in order for me to modify cookies successfully I had to use driver.delete_all_cookies() after visiting the domain and before setting the specific cookie I'm after.