如何在Selenium Webdriver中使用现有的配置文件?

7

我正在尝试按照标题所说的方式,使用Python的{{link1:Selenium Webdriver}},使用存储在<PROFILE-DIR>中的现有Firefox配置文件。

我尝试过的方法:

  • 在驱动程序上使用了{{link2:options.profile}}选项:
#!/usr/bin/env python

from selenium.webdriver.firefox.firefox_profile import FirefoxProfile
from selenium.webdriver import Firefox, DesiredCapabilities
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.firefox.options import Options

options = Options()
options.profile = '<PROFILE_DIR>'
webdriver = Firefox(options=options)

这将现有的配置文件复制到临时位置。我可以看到它起作用,因为我启动的新会话可以访问配置文件的旧cookie等。但这不是我想要的:我想要在原地使用配置文件。
  • 尝试将配置文件作为“--profile”传递给args capability:将上面的代码更改为
capabilities = DesiredCapabilities.FIREFOX.copy()
capabilities['args'] = '--profile <PROFILE-DIR>'
webdriver = Firefox(desired_capabilities=capabilities)

没有任何操作:关闭会话后查看 geckodriver.log 仍然显示像这样的内容:Running command: "/usr/bin/firefox" "--marionette" "-foreground" "-no-remote" "-profile" "/tmp/rust_mozprofileOFKY46",即仍在使用临时配置文件(甚至不是现有配置文件的副本;旧的 cookie 也不在其中)。

  • 尝试使用 capabilities['args'] = ['-profile', '<PROFILE-DIR>'] 进行相同的操作(即将其设置为字符串列表而不是单个字符串),结果相同。

  • 阅读了一堆其他的 SO 帖子,但都没有解决方法。这主要是因为它们是针对 Chrome 的(你可以向该驱动程序传递命令行选项;我没有看到类似于 geckodriver 的东西),或者因为它们回退到现有配置文件的副本。

在这方面,最相关的答案基本上实施了我想到的同样的方法:

  1. 使用上述所描述的 options.profile,以现有配置文件的副本启动驱动程序;

  2. 在完成后手动关闭驱动程序实例(例如,使用 Ctrl+CSIGINT),以便临时配置文件目录不被删除;

  3. 复制现有配置文件上留下的所有内容,从而可以访问您在自动会话中需要的任何剩余部分。

这样做看起来很繁琐且似乎是多余的。此外,geckodriver 未能删除临时配置文件(我将依赖它)被认为是一个错误。

我肯定是对如何传递上述功能选项有所误解,或者类似的情况。但是文档可以更好地提供示例。

1个回答

1
我想出了一种解决方案,允许用户通过动态传递环境变量的方式,在原地使用Firefox配置文件来运行Geckodriver。
我首先下载了Geckodriver 0.32.0,并且使得你只需要通过环境变量FIREFOX_PROFILE_DIR提供Firefox配置文件目录即可。
代码更改在src/browser.rs,第88行,将以下内容替换:
    let mut profile = match options.profile {
        ProfileType::Named => None,
        ProfileType::Path(x) => Some(x),
        ProfileType::Temporary => Some(Profile::new(profile_root)?),
    };

使用:

    let mut profile = if let Ok(profile_dir) = std::env::var("FIREFOX_PROFILE_DIR") {
        Some(Profile::new_from_path(Path::new(&profile_dir))?)
    } else {
        match options.profile {
            ProfileType::Named => None,
            ProfileType::Path(x) => Some(x),
            ProfileType::Temporary => Some(Profile::new(profile_root)?),
        }
    };

您可以参考我的Git提交记录,以查看与原始Geckodriver代码的差异。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接