如何使用 Selenium 处理证书?
- 2025-02-27 09:07:00
- admin 原创
- 51
问题描述:
我正在使用Selenium启动浏览器。我该如何处理要求浏览器接受或不接受证书的网页(URL)?
在 Firefox 中,可能会有这样的网站要求我接受其证书,如下所示:
在 Internet Explorer 浏览器上,我可能会看到如下内容:
在 Google Chrome 上:
我重复我的问题:当我使用 Selenium(Python 编程语言)启动浏览器(Internet Explorer、Firefox 和 Google Chrome)时,如何自动接受网站的证书?
解决方案 1:
对于 Firefox,您需要将accept_untrusted_certs
FirefoxProfile()
选项设置为True
:
from selenium import webdriver
profile = webdriver.FirefoxProfile()
profile.accept_untrusted_certs = True
driver = webdriver.Firefox(firefox_profile=profile)
driver.get('https://cacert.org/')
driver.close()
对于 Chrome,您需要添加参数:--ignore-certificate-errors
ChromeOptions()
from selenium import webdriver
options = webdriver.ChromeOptions()
options.add_argument('ignore-certificate-errors')
driver = webdriver.Chrome(chrome_options=options)
driver.get('https://cacert.org/')
driver.close()
对于 Internet Explorer,您需要设置acceptSslCerts
所需的功能:
from selenium import webdriver
capabilities = webdriver.DesiredCapabilities().INTERNETEXPLORER
capabilities['acceptSslCerts'] = True
driver = webdriver.Ie(capabilities=capabilities)
driver.get('https://cacert.org/')
driver.close()
实际上,根据Desired Capabilities
文档,将acceptSslCerts
功能设置为True
应该适用于所有浏览器,因为它是一种通用的读/写功能:
接受 SslCerts
布尔值
会话是否应默认接受所有 SSL 证书。
Firefox 的工作演示:
>>> from selenium import webdriver
设置acceptSslCerts
为False
:
>>> capabilities = webdriver.DesiredCapabilities().FIREFOX
>>> capabilities['acceptSslCerts'] = False
>>> driver = webdriver.Firefox(capabilities=capabilities)
>>> driver.get('https://cacert.org/')
>>> print(driver.title)
Untrusted Connection
>>> driver.close()
设置acceptSslCerts
为True
:
>>> capabilities = webdriver.DesiredCapabilities().FIREFOX
>>> capabilities['acceptSslCerts'] = True
>>> driver = webdriver.Firefox(capabilities=capabilities)
>>> driver.get('https://cacert.org/')
>>> print(driver.title)
Welcome to CAcert.org
>>> driver.close()
解决方案 2:
对于 Firefox:
ProfilesIni profile = new ProfilesIni();
FirefoxProfile myprofile = profile.getProfile("default");
myprofile.setAcceptUntrustedCertificates(true);
myprofile.setAssumeUntrustedCertificateIssuer(true);
WebDriver driver = new FirefoxDriver(myprofile);
对于Chrome我们可以使用:
DesiredCapabilities capabilities = DesiredCapabilities.chrome();
capabilities.setCapability("chrome.switches", Arrays.asList("--ignore-certificate-errors"));
driver = new ChromeDriver(capabilities);
对于Internet Explorer,我们可以使用:
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
Webdriver driver = new InternetExplorerDriver(capabilities);
解决方案 3:
对于 Firefox Python:
Firefox 自签名证书错误现已修复:
使用 marionette firefox webdrive python splinter 接受 ssl 证书
“acceptSslCerts” 应替换为“acceptInsecureCerts”
from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
from selenium.webdriver.firefox.firefox_binary import FirefoxBinary
caps = DesiredCapabilities.FIREFOX.copy()
caps['acceptInsecureCerts'] = True
ff_binary = FirefoxBinary("path to the Nightly binary")
driver = webdriver.Firefox(firefox_binary=ff_binary, capabilities=caps)
driver.get("https://expired.badssl.com")
解决方案 4:
对于通过 python selenium 来了解与无头 chrome 相关的问题的人来说,您可能会发现https://bugs.chromium.org/p/chromium/issues/detail?id=721739#c102很有用。
看起来你可以这样做
chrome_options = Options()
chrome_options.add_argument('--allow-insecure-localhost')
或者类似下面的内容(可能需要适应python):
ChromeOptions options = new ChromeOptions()
DesiredCapabilities caps = DesiredCapabilities.chrome()
caps.setCapability(ChromeOptions.CAPABILITY, options)
caps.setCapability("acceptInsecureCerts", true)
WebDriver driver = new ChromeDriver(caps)
解决方案 5:
在 C# (.net core) 中使用Selenium.Webdriver
如下Selenium.Chrome.Webdriver
:
ChromeOptions options = new ChromeOptions();
options.AddArgument("--ignore-certificate-errors");
using (var driver = new ChromeDriver(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location),options))
{
...
}
解决方案 6:
ChromeOptions options = new ChromeOptions().addArguments("--proxy-server=http://" + proxy);
options.setAcceptInsecureCerts(true);
解决方案 7:
JavaScript的:
const capabilities = webdriver.Capabilities.phantomjs();
capabilities.set(webdriver.Capability.ACCEPT_SSL_CERTS, true);
capabilities.set(webdriver.Capability.SECURE_SSL, false);
capabilities.set('phantomjs.cli.args', ['--web-security=no', '--ssl-protocol=any', '--ignore-ssl-errors=yes']);
const driver = new webdriver.Builder().withCapabilities(webdriver.Capabilities.chrome(), capabilities).build();
解决方案 8:
在 selenium python 中,需要设置desired_capabilities
为:
desired_capabilities = {
"acceptInsecureCerts": True
}
解决方案 9:
我在使用 Selenium 和 Behat 时遇到了同样的问题。如果您想通过 传递参数behat.yml
,它需要如下所示:
default:
extensions:
BehatMinkExtension:
base_url: https://my-app.com
default_session: selenium2
selenium2:
browser: firefox
capabilities:
extra_capabilities:
acceptInsecureCerts: true
解决方案 10:
创建配置文件,然后创建驱动程序可以帮助我们解决 Firefox 中的证书问题:
var profile = new FirefoxProfile();
profile.SetPreference("network.automatic-ntlm-auth.trusted-uris","DESIREDURL");
driver = new FirefoxDriver(profile);
解决方案 11:
对于那些使用Firefox遇到此问题并且上述解决方案不起作用的人,您可以尝试下面的代码(我最初的答案在这里)。
from selenium import webdriver
profile = webdriver.FirefoxProfile()
profile.DEFAULT_PREFERENCES['frozen']['marionette.contentListener'] = True
profile.DEFAULT_PREFERENCES['frozen']['network.stricttransportsecurity.preloadlist'] = False
profile.DEFAULT_PREFERENCES['frozen']['security.cert_pinning.enforcement_level'] = 0
profile.set_preference('webdriver_assume_untrusted_issuer', False)
profile.set_preference("browser.download.folderList", 2)
profile.set_preference("browser.download.manager.showWhenStarting", False)
profile.set_preference("browser.download.dir", temp_folder)
profile.set_preference("browser.helperApps.neverAsk.saveToDisk",
"text/plain, image/png")
driver = webdriver.Firefox(firefox_profile=profile)
解决方案 12:
WebDriverManager.chromedriver().setup();
ChromeOptions options = new ChromeOptions();
options.addArguments("--ignore-certificate-errors");
driver = new ChromeDriver(options);
我已经在 Chrome 浏览器上用过它了,效果很好
解决方案 13:
从浏览器的证书存储区中删除除必要证书之外的所有证书,然后将浏览器配置为在只有一个证书时自动选择该证书。
解决方案 14:
仅关于此问题的最新消息。
需要驱动程序:
Linux: Centos 7 64bit, Window 7 64bit
Firefox: 52.0.3
Selenium Webdriver: 3.4.0 (Windows), 3.8.1 (Linux Centos)
GeckoDriver: v0.16.0 (Windows), v0.17.0 (Linux Centos)
代码
System.setProperty("webdriver.gecko.driver", "/home/seleniumproject/geckodrivers/linux/v0.17/geckodriver");
ProfilesIni ini = new ProfilesIni();
// Change the profile name to your own. The profile name can
// be found under .mozilla folder ~/.mozilla/firefox/profile.
// See you profile.ini for the default profile name
FirefoxProfile profile = ini.getProfile("default");
DesiredCapabilities cap = new DesiredCapabilities();
cap.setAcceptInsecureCerts(true);
FirefoxBinary firefoxBinary = new FirefoxBinary();
GeckoDriverService service =new GeckoDriverService.Builder(firefoxBinary)
.usingDriverExecutable(new
File("/home/seleniumproject/geckodrivers/linux/v0.17/geckodriver"))
.usingAnyFreePort()
.usingAnyFreePort()
.build();
try {
service.start();
} catch (IOException e) {
e.printStackTrace();
}
FirefoxOptions options = new FirefoxOptions().setBinary(firefoxBinary).setProfile(profile).addCapabilities(cap);
driver = new FirefoxDriver(options);
driver.get("https://www.google.com");
System.out.println("Life Title -> " + driver.getTitle());
driver.close();
解决方案 15:
我能够使用 PhantomJSDriver 和 selenium web driver 3.1 在 .net c# 上执行此操作
[TestMethod]
public void headless()
{
var driverService = PhantomJSDriverService.CreateDefaultService(@"C:Driverphantomjs\");
driverService.SuppressInitialDiagnosticInformation = true;
driverService.AddArgument("--web-security=no");
driverService.AddArgument("--ignore-ssl-errors=yes");
driver = new PhantomJSDriver(driverService);
driver.Navigate().GoToUrl("XXXXXX.aspx");
Thread.Sleep(6000);
}
解决方案 16:
每当我在使用较新的浏览器时遇到此问题时,我只需使用 AppRobotic 个人版单击特定的屏幕坐标,或浏览按钮并单击。
基本上,它只是使用其宏功能,但在无头设置上不起作用。
解决方案 17:
我遇到了完全相同的问题。但是,当我尝试在浏览器中手动打开网站时,证书是正确的,但在详细信息中,名称为“DONOTTRUST”。
证书的差异是由于 Fiddler 在后台运行并解密所有 HTTPS 内容然后重新加密造成的。
要解决我的问题,只需关闭机器上的 Fiddler。如果您需要保持 Fiddler 处于打开状态,则可以在 Fiddler 设置中取消选中“解密 SSL”。
解决方案 18:
对于.NET,对我有用的是以下内容...
var chromeOptions = new ChromeOptions { AcceptInsecureCertificates = true };
实际上,它告诉 ChromeDriver 选项在检测到不安全的证书时不要停止浏览器执行,而是正常进行。
解决方案 19:
简单的方法,
from selenium import webdriver
from selenium.webdriver.chrome.service import Service as ChromeService
# pip install webdriver-manager
from webdriver_manager.chrome import ChromeDriverManager
def get_chrome_capabilities():
caps = webdriver.DesiredCapabilities.CHROME
caps['acceptSslCerts'] = True
caps['acceptInsecureCerts'] = True
opts = webdriver.ChromeOptions()
caps.update(opts.to_capabilities())
return caps
# ChromeDriveManager to automate and download webdriver
service = ChromeService(executable_path=ChromeDriverManager().install())
driver = webdriver.Chrome(
service=service,
desired_capabilities=get_chrome_capabilities(),
)
# Use this instead of the above if you are already setup
# driver = webdriver.Chrome(desired_capabilities=get_chrome_capabilities())
driver.get("http://www.google.com")
assert "google" in driver.page_source
driver.quit()
解决方案 20:
以下是使用 powershell 和 firefox 自动执行此操作的方法:
import-module Selenium
$ffoptions = [OpenQA.Selenium.Firefox.FirefoxOptions]::new()
$ffoptions.AddAdditionalCapability([OpenQA.Selenium.Remote.CapabilityType]::AcceptInsecureCertificates, $true, $true)
$ffoptions.toCapabilities()
$Driver = New-Object OpenQA.Selenium.Firefox.Firefoxdriver($ffoptions)
enter-seUrl "https://www.google.co.uk" -Driver $Driver
解决方案 21:
看起来它仍然没有对这个问题的标准解决方案。换句话说 - 你仍然不能说“好吧,做一个认证,无论你是 Internet Explorer、Mozilla 还是 Google Chrome”。但我找到了一篇文章,展示了如何在 Mozilla Firefox 中解决这个问题。如果你对此感兴趣,你可以在这里查看。
扫码咨询,免费领取项目管理大礼包!