Python: use cookie to login with Selenium

2020-01-31 04:01发布

What I want to do is to open a page (for example youtube) and be automatically logged in, like when I manually open it in the browser.

From what I've understood, I have to use cookies, the problem is that I can't understand how.

I tried to download youtube cookies with this:

driver = webdriver.Firefox(executable_path="driver/geckodriver.exe")
driver.get("https://www.youtube.com/")
print(driver.get_cookies())

And what I get is:

{'name': 'VISITOR_INFO1_LIVE', 'value': 'EDkAwwhbDKQ', 'path': '/', 'domain': '.youtube.com', 'expiry': None, 'secure': False, 'httpOnly': True}

So what cookie do I have to load to automatically log in?

3条回答
走好不送
2楼-- · 2020-01-31 04:18

You can use pickle to save cookies as text file and load it later:

def save_cookie(driver, path):
    with open(path, 'wb') as filehandler:
        pickle.dump(driver.get_cookies(), filehandler)

def load_cookie(driver, path):
     with open(path, 'rb') as cookiesfile:
         cookies = pickle.load(cookiesfile)
         for cookie in cookies:
             driver.add_cookie(cookie)
查看更多
再贱就再见
3楼-- · 2020-01-31 04:24

I ever met the same issue. Finally I use the chromeoptions to fix this issue instead of cookie file.

    import getpass

    chrome_options = webdriver.ChromeOptions()
    chrome_options.add_argument("user-data-dir=C:\\Users\\"+getpass.getuser()+"\\AppData\\Local\\Google\\Chrome\\User Data\\Default")  # this is the directory for the cookies

    driver = webdriver.Chrome(chrome_options=chrome_options)
    driver.get(url)
查看更多
家丑人穷心不美
4楼-- · 2020-01-31 04:35
登录 后发表回答