Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selenium Chromedriver add cookie - invalid domain error

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

like image 268
j doe Avatar asked Jan 10 '17 00:01

j doe


Video Answer


1 Answers

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)

    # delete the current cookies
    driver.delete_all_cookies()

    # 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 is initialized with default url data:.
  2. add_cookie() requires the current url to be under the same domain pattern as the cookie.
  3. data: will not match any cookie domain

So, you get invalid cookie domain error.

like image 159
Edison A Avatar answered Sep 24 '22 17:09

Edison A