Python硒:使用已经打开并使用登录凭证登录的浏览器

TJ1*_*TJ1 8 python selenium python-3.x selenium-webdriver

对于使用硒的python程序的不同运行,是否有办法让我使用自己的凭据保留已打开并登录的浏览器,并在以后的运行中打开并使用?

我正在调试代码。每次需要在浏览器上使用我的凭据登录时。当前,每次我停止代码时,网络浏览器都会关闭。有没有办法保持我已经打开并已登录的浏览器的副本,并在以后的调试中使用它,以便每次无需再次输入登录凭据?

我打开浏览器的代码如下:

driver = webdriver.Chrome(executable_path="/the_path/chromedriver", chrome_options=chrome_options) 
driver.get(url)
Run Code Online (Sandbox Code Playgroud)

编辑:

实际上,该网站要求进行身份验证的方式如下:首先,它要求输入用户名,然后我需要按继续按钮,然后要求输入密码,输入密码后,它将SMS发送到我的手机,在进入预期页面之前,我需要输入它。

Edu*_*scu 5

这是一个功能请求,因为不可行而关闭。但这是一种方法,使用文件夹作为配置文件,并通过使用 Chrome 选项将所有登录从一个会话保持到另一个会话user-data-dir,以便将文件夹用作配置文件,我运行:

chrome_options = Options()
chrome_options.add_argument("user-data-dir=selenium") 
driver = webdriver.Chrome(chrome_options=chrome_options)
driver.get("www.google.com")
Run Code Online (Sandbox Code Playgroud)

您可以在这一步与打开的窗口手动交互,并进行检查人机交互的登录,检查记住密码等我这样做,然后登录,我现在需要的 cookie 每次我使用该文件夹启动 Webdriver 时,一切都在那里。您还可以手动安装扩展并在每个会话中使用它们。第二次运行时,使用与上面完全相同的代码,所有设置、cookie 和登录都在那里:

chrome_options = Options()
chrome_options.add_argument("user-data-dir=selenium") 
driver = webdriver.Chrome(chrome_options=chrome_options)
driver.get("www.google.com") #Now you can see  the cookies, the settings, Extensions and the logins done in the previous session are present here
Run Code Online (Sandbox Code Playgroud)

好处是可以使用多个不同设置和cookies的文件夹,扩展程序无需加载、卸载cookies、安装卸载扩展程序、更改设置、通过代码更改登录,从而没有程序中断的逻辑,等等 此外,这比必须通过代码完成所有工作更快。


Aro*_*unt 5

好吧,由于此问题已被通过,但我的重复问题的标记未被接受,我将在此处发布与我已经针对类似问题发布的完全相同的答案


您可以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)
Run Code Online (Sandbox Code Playgroud)

使用如下脚本:

from selenium import webdriver
from afile import save_cookie

driver = webdriver.Chrome()
driver.get('http://website.internets')

foo = input()

save_cookie(driver, '/tmp/cookie')
Run Code Online (Sandbox Code Playgroud)

您可以做的是:

  1. 运行这个脚本
  2. 在(硒的)浏览器上,转到网站,登录
  3. 返回您的终端,输入任何内容,然后按Enter。
  4. 在享受您的Cookie文件/tmp/cookie。现在,您可以将其复制到代码仓库中,并在需要时将其打包到您的应用中。

因此,现在,在您的主应用程序代码中:

from afile import load_cookie

driver = webdriver.Chrome()
load_cookie(driver, 'path/to/cookie')
Run Code Online (Sandbox Code Playgroud)

现在您已登录。