Python:使用cookie登录Selenium

时间:2017-07-31 13:30:07

标签: python selenium

我想要做的是打开一个页面(例如youtube)并自动登录,就像我在浏览器中手动打开它一样。

据我所知,我必须使用cookies,问题是我无法理解。

我尝试下载youtube cookies:

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

我得到的是:

  

{'name':'VISITOR_INFO1_LIVE','value':'EDkAwwhbDKQ','path':'/','domain':'。youtube.com','expiry':无,'secure':False ,'httpOnly':真实}

那么我必须加载哪些cookie才能自动登录?

6 个答案:

答案 0 :(得分:7)

您可以使用pickle将Cookie保存为文本文件并稍后加载:

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)

答案 1 :(得分:1)

试试这个,有一种方法可以将cookie添加到您的驱动程序会话

http://selenium-python.readthedocs.io/api.html#selenium.webdriver.remote.webdriver.WebDriver.add_cookie

答案 2 :(得分:1)

我建议使用json格式,因为cookie本质上是字典和列表。否则,这是approved answer

import json

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

def load_cookie(driver, path):
    with open(path, 'r') as cookiesfile:
        cookies = json.load(cookiesfile)
    for cookie in cookies:
        driver.add_cookie(cookie)

答案 3 :(得分:0)

我曾经遇到过同样的问题。最后,我使用chromeoptions而不是cookie文件来解决此问题。

    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 :(得分:0)

我有一种情况,我想重用一次经过身份验证/登录的会话。我正在同时使用多个浏览器。

我已经尝试了博客和StackOverflow答案中的许多解决方案。

1.使用用户数据目录和配置文件目录

这些镶边选项可以解决您每次打开一个浏览器的目的,但是如果您打开多个窗口,则会抛出一个错误,提示user data directory is already in use

2.使用Cookie

可以在多个浏览器之间共享Cookie。 SO答案中可用的代码是如何在硒中使用Cookie的大部分重要内容。在这里,我将扩展这些解决方案以完成流程。

代码

# selenium-driver.py
import pickle
from selenium import webdriver


class SeleniumDriver(object):
    def __init__(
        self,
        # chromedriver path
        driver_path='/Users/username/work/chrome/chromedriver',
        # pickle file path to store cookies
        cookies_file_path='/Users/username/work/chrome/cookies.pkl',
        # list of websites to reuse cookies with
        cookies_websites=["https://facebook.com"]

    ):
        self.driver_path = driver_path
        self.cookies_file_path = cookies_file_path
        self.cookies_websites = cookies_websites
        chrome_options = webdriver.ChromeOptions()
        self.driver = webdriver.Chrome(
            executable_path=self.driver_path,
            options=chrome_options
        )
        try:
            # load cookies for given websites
            cookies = pickle.load(open(self.cookies_file_path, "rb"))
            for website in self.cookies_websites:
                self.driver.get(website)
                for cookie in cookies:
                    self.driver.add_cookie(cookie)
                self.driver.refresh()
        except Exception as e:
            # it'll fail for the first time, when cookie file is not present
            print(str(e))
            print("Error loading cookies")

    def save_cookies(self):
        # save cookies
        cookies = self.driver.get_cookies()
        pickle.dump(cookies, open(self.cookies_file_path, "wb"))

    def close_all(self):
        # close all open tabs
        if len(self.driver.window_handles) < 1:
            return
        for window_handle in self.driver.window_handles[:]:
            self.driver.switch_to.window(window_handle)
            self.driver.close()

    def quit(self):
        self.save_cookies()
        self.close_all()


def is_fb_logged_in():
    driver.get("https://facebook.com")
    if 'Facebook – log in or sign up' in driver.title:
        return False
    else:
        return True


def fb_login(username, password):
    username_box = driver.find_element_by_id('email')
    username_box.send_keys(username)

    password_box = driver.find_element_by_id('pass')
    password_box.send_keys(password)

    login_box = driver.find_element_by_id('loginbutton')
    login_box.click()


if __name__ == '__main__':
    """
    Run  - 1
    First time authentication and save cookies

    Run  - 2
    Reuse cookies and use logged-in session
    """
    selenium_object = SeleniumDriver()
    driver = selenium_object.driver
    username = "fb-username"
    password = "fb-password"

    if is_fb_logged_in(driver):
        print("Already logged in")
    else:
        print("Not logged in. Login")
        fb_login(username, password)

    selenium_object.quit()

运行1:登录并保存Cookie

$ python selenium-driver.py
[Errno 2] No such file or directory: '/Users/username/work/chrome/cookies.pkl'
Error loading cookies
Not logged in. Login

这将打开facebook登录窗口,并输入用户名密码进行登录。登录后,将关闭浏览器并保存cookie。

运行2:重用cookie继续登录会话

$ python selenium-driver.py
Already logged in

这将使用存储的cookie打开Facebook登录会话。

要求

  • Python 3.7
  • Selenium Webdriver
  • Pickle

答案 5 :(得分:0)

这是一种可能的解决方案

import pickle
from selenium import webdriver

def save_cookie(driver):
    with open("cookie", 'wb') as filehandler:
        pickle.dump(driver.get_cookies(), filehandler)
def load_cookie(driver):
     with open("cookie", 'rb') as cookiesfile:
         cookies = pickle.load(cookiesfile)
         for cookie in cookies:
             print(cookie)
             driver.add_cookie(cookie)

driver = webdriver.Chrome(ChromeDriverManager().install())
url = 'https://www.Youtube.com'
driver.get(url)
#first try to login and generate cookies after that you can use cookies to login eveytime 
load_cookie(driver)
# Do you task here 
save_cookie(driver)
driver.quit()