Python:使用 cookie 登录 Selenium



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

据我所知,我必须使用cookie,问题是我不明白如何。

我试图用这个下载YouTube饼干:

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': None, 'secure': False, 'httpOnly': True}

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

您可以使用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)

我建议使用json格式,因为cookie本质上是字典和列表。否则,这是批准的答案。

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)

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

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

1. 使用用户数据目录和配置文件目录如果您一次打开一个浏览器,这些 chrome 选项可以解决问题,但如果您打开多个窗口,它会抛出一条错误消息,指出user data directory is already in use.

2. 使用饼干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

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

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

$ python selenium-driver.py
Already logged in

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

要求

  • 蟒蛇 3.7
  • 硒网络驱动程序
  • 泡菜

这是一个可能的解决方案

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()

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

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

我曾经遇到过同样的问题。最后,我使用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)

最新更新