2021 年 5 月 30 日更新后
这是我在 Stack Overflow 上尝试过的最难回答的问题。因为它涉及用多种语言(Java、Rust 和 C++)编写的多个代码库的交互。这种复杂性使问题可能无法解决。
我最后一次破解这个可能无法解决的问题:
在您问题的代码中,您正在修改文件 user.js 此文件仍由 Selenium 使用。
public FirefoxProfile() {
this(null);
}
/**
* Constructs a firefox profile from an existing profile directory.
* <p>
* Users who need this functionality should consider using a named profile.
*
* @param profileDir The profile directory to use as a model.
*/
public FirefoxProfile(File profileDir) {
this(null, profileDir);
}
@Beta
protected FirefoxProfile(Reader defaultsReader, File profileDir) {
if (defaultsReader == null) {
defaultsReader = onlyOverrideThisIfYouKnowWhatYouAreDoing();
}
additionalPrefs = new Preferences(defaultsReader);
model = profileDir;
verifyModel(model);
File prefsInModel = new File(model, "user.js");
if (prefsInModel.exists()) {
StringReader reader = new StringReader("{\"frozen\": {}, \"mutable\": {}}");
Preferences existingPrefs = new Preferences(reader, prefsInModel);
acceptUntrustedCerts = getBooleanPreference(existingPrefs, ACCEPT_UNTRUSTED_CERTS_PREF, true);
untrustedCertIssuer = getBooleanPreference(existingPrefs, ASSUME_UNTRUSTED_ISSUER_PREF, true);
existingPrefs.addTo(additionalPrefs);
} else {
acceptUntrustedCerts = true;
untrustedCertIssuer = true;
}
// This is not entirely correct but this is not stored in the profile
// so for now will always be set to false.
loadNoFocusLib = false;
try {
defaultsReader.close();
} catch (IOException e) {
throw new WebDriverException(e);
}
}
所以理论上你应该可以修改geckodriver源代码中的capabilities.rs。该文件包含 temp_dir。
正如我在理论上所说的那样,因为当我查看 Firefox 源代码时,它的 temp_dir 分布在整个代码库中。
2021 年 5 月 26 日原帖
我不确定您是否可以阻止 Selenium 创建临时 Firefox 配置文件。
来自gecko documents:
“配置文件是在系统临时文件夹中创建的。这也是在提供配置文件时提取编码配置文件的位置。默认情况下,geckodriver 将在此位置创建一个新配置文件 em>。”
我目前看到的唯一解决方案是要求您修改 Geckodriver 源文件以防止创建临时文件夹/配置文件。
我目前正在查看源代码。这些文件可能是正确的,但我需要更多地查看源代码:
这里还有一些需要梳理的文件:
https://searchfox.org/mozilla-central/search?q=tempfile&path=
这看起来很有希望:
https://searchfox.org/mozilla-central/source/testing/geckodriver/doc/Profiles.md
"geckodriver 使用 [profiles] 来检测 Firefox 的行为。
用户通常会依赖 geckodriver 生成一个临时的,
一次性配置文件。当 WebDriver 删除这些配置文件
会话到期。
如果用户需要使用自定义的、准备好的配置文件,
geckodriver 将对配置文件进行修改,以确保
正确的行为。请参阅下面的 [自动化偏好]
在这种情况下,用户定义的首选项的优先级。
可以通过两种不同的方式提供自定义配置文件:
1.通过将--profile /some/location 附加到[args 能力],
这将指示 geckodriver 就地使用配置文件;
我在尝试这样做时发现了这个问题:how do I use an existing profile in-place with Selenium Webdriver?
这里还有一个在 Github 上的 selenium 中提出的关于临时目录的问题。 https://github.com/SeleniumHQ/selenium/issues/8645
翻阅geckodriver v0.29.1的源码,我发现了一个加载配置文件的文件。
来源:capabilities.rs
fn load_profile(options: &Capabilities) -> WebDriverResult<Option<Profile>> {
if let Some(profile_json) = options.get("profile") {
let profile_base64 = profile_json.as_str().ok_or_else(|| {
WebDriverError::new(ErrorStatus::InvalidArgument, "Profile is not a string")
})?;
let profile_zip = &*base64::decode(profile_base64)?;
// Create an emtpy profile directory
let profile = Profile::new()?;
unzip_buffer(
profile_zip,
profile
.temp_dir
.as_ref()
.expect("Profile doesn't have a path")
.path(),
)?;
Ok(Some(profile))
} else {
Ok(None)
}
}
来源:marionette.rs
fn start_browser(&mut self, port: u16, options: FirefoxOptions) -> WebDriverResult<()> {
let binary = options.binary.ok_or_else(|| {
WebDriverError::new(
ErrorStatus::SessionNotCreated,
"Expected browser binary location, but unable to find \
binary in default location, no \
'moz:firefoxOptions.binary' capability provided, and \
no binary flag set on the command line",
)
})?;
let is_custom_profile = options.profile.is_some();
let mut profile = match options.profile {
Some(x) => x,
None => Profile::new()?,
};
self.set_prefs(port, &mut profile, is_custom_profile, options.prefs)
.map_err(|e| {
WebDriverError::new(
ErrorStatus::SessionNotCreated,
format!("Failed to set preferences: {}", e),
)
})?;
let mut runner = FirefoxRunner::new(&binary, profile);
runner.arg("--marionette");
if self.settings.jsdebugger {
runner.arg("--jsdebugger");
}
if let Some(args) = options.args.as_ref() {
runner.args(args);
}
// https://developer.mozilla.org/docs/Environment_variables_affecting_crash_reporting
runner
.env("MOZ_CRASHREPORTER", "1")
.env("MOZ_CRASHREPORTER_NO_REPORT", "1")
.env("MOZ_CRASHREPORTER_SHUTDOWN", "1");
let browser_proc = runner.start().map_err(|e| {
WebDriverError::new(
ErrorStatus::SessionNotCreated,
format!("Failed to start browser {}: {}", binary.display(), e),
)
})?;
self.browser = Some(Browser::Host(browser_proc));
Ok(())
}
pub fn set_prefs(
&self,
port: u16,
profile: &mut Profile,
custom_profile: bool,
extra_prefs: Vec<(String, Pref)>,
) -> WebDriverResult<()> {
let prefs = profile.user_prefs().map_err(|_| {
WebDriverError::new(
ErrorStatus::UnknownError,
"Unable to read profile preferences file",
)
})?;
for &(ref name, ref value) in prefs::DEFAULT.iter() {
if !custom_profile || !prefs.contains_key(name) {
prefs.insert((*name).to_string(), (*value).clone());
}
}
prefs.insert_slice(&extra_prefs[..]);
if self.settings.jsdebugger {
prefs.insert("devtools.browsertoolbox.panel", Pref::new("jsdebugger"));
prefs.insert("devtools.debugger.remote-enabled", Pref::new(true));
prefs.insert("devtools.chrome.enabled", Pref::new(true));
prefs.insert("devtools.debugger.prompt-connection", Pref::new(false));
}
prefs.insert("marionette.log.level", logging::max_level().into());
prefs.insert("marionette.port", Pref::new(port));
prefs.write().map_err(|e| {
WebDriverError::new(
ErrorStatus::UnknownError,
format!("Unable to write Firefox profile: {}", e),
)
})
}
}
查看 gecko 源代码后,看起来 mozprofile::profile::Profile 来自 FireFox 而不是 geckodriver
当您迁移到 Selenium 4 时,您可能会遇到配置文件问题。
参考:https://github.com/SeleniumHQ/selenium/issues/9417
对于 Selenium 4,我们不推荐使用配置文件,因为我们可以采取其他机制来加快启动速度。
请使用 Options 类来设置您需要的首选项,如果您需要使用插件,请使用 driver.install_addon("path/to/addon")
您可以通过 pip install selenium --pre
安装处于测试阶段的 selenium 4
我在您的代码中注意到您正在写入 user.js,这是 FireFox 的自定义文件。您是否考虑过在 Gecko 之外手动创建这些文件?
你也看过mozprofile吗?