V
V
Valery Orlov2019-10-30 13:04:48
Python
Valery Orlov, 2019-10-30 13:04:48

How to use cookies to enter your personal account on Selenium?

All good.
By logging in to my personal account, I save a cookie for subsequent logins:

from selenium import webdriver 
import pickle
import time

chromedriver = 'D:\\temp\\selenium\\chromedriver.exe'
options = webdriver.ChromeOptions()
options.add_argument("user-agent=Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.70 Safari/537.36");
browser = webdriver.Chrome(executable_path=chromedriver, chrome_options=options)
browser.get('https://example.com/login/')
email = browser.find_element_by_id('accountName')
email.clear()
password = browser.find_element_by_id('password')
password.clear()
login = browser.find_element_by_id('submit')
email.send_keys('my_mail')
password.send_keys('my_pass')
login.click()
time.sleep(20)
pickle.dump(browser.get_cookies() , open("cookies.pkl","wb"))
browser.close()
browser = webdriver.Chrome(executable_path=chromedriver, chrome_options=options)
cookies = pickle.load(open("cookies.pkl","rb"))
browser.delete_all_cookies()
for cookie in cookies:
    browser.add_cookie(cookie)

browser.get('https://example.com/login/')

As a result I get this error:
Traceback (most recent call last):
  File "cookie1.py", line 54, in <module>
    browser.add_cookie(cookie)
  File "C:\Users\User\AppData\Local\Programs\Python\Python37\lib\site-packages\se
lenium\webdriver\remote\webdriver.py", line 894, in add_cookie
    self.execute(Command.ADD_COOKIE, {'cookie': cookie_dict})
  File "C:\Users\User\AppData\Local\Programs\Python\Python37\lib\site-packages\se
lenium\webdriver\remote\webdriver.py", line 321, in execute
    self.error_handler.check_response(response)
  File "C:\Users\User\AppData\Local\Programs\Python\Python37\lib\site-packages\se
lenium\webdriver\remote\errorhandler.py", line 242, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.InvalidCookieDomainException: Message: invalid cookie
 domain
  (Session info: chrome=78.0.3904.70)

There seems to be a problem with the domain. But how to solve it?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
alternativshik, 2019-10-30
@lungdesire29

You must first make a request to the site, and then hang cookies.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question