乐闻世界logo
搜索文章和话题

How to handle the HTTPS website in Selenium or how to accept the SSL untrusted connection?

1 个月前提问
1 个月前修改
浏览次数12

1个答案

1

在使用Selenium进行自动化测试时,处理HTTPS网站或接受SSL不受信任的连接是一项常见的任务。这通常涉及到配置浏览器驱动以信任所有SSL证书,即使它们是自签名的或者不被认可的证书。下面我将详细说明如何在一些常用的浏览器中配置这些设置:

1. Chrome浏览器

对于Chrome浏览器,可以通过设置ChromeOptions来达到接受不受信任SSL证书的目的。下面是一个如何设置的示例:

python
from selenium import webdriver from selenium.webdriver.chrome.options import Options chrome_options = Options() chrome_options.add_argument('--ignore-certificate-errors') # 忽略证书错误 driver = webdriver.Chrome(executable_path='path_to_chromedriver', options=chrome_options) driver.get('https://example.com')

这里,使用--ignore-certificate-errors参数来告诉Chrome浏览器忽略SSL证书错误。

2. Firefox浏览器

对于Firefox浏览器,可以通过修改FirefoxProfile来接受不受信任的SSL证书。

python
from selenium import webdriver from selenium.webdriver.firefox.options import Options as FirefoxOptions firefox_options = FirefoxOptions() firefox_profile = webdriver.FirefoxProfile() firefox_profile.accept_untrusted_certs = True # 接受不受信任的证书 driver = webdriver.Firefox(executable_path='path_to_geckodriver', firefox_profile=firefox_profile, options=firefox_options) driver.get('https://example.com')

在这个例子中,accept_untrusted_certs属性被设置为True,这表明Firefox应该接受所有不受信任的证书。

3. Edge浏览器

对于Edge浏览器,处理方式与Chrome类似,因为它们都是基于Chromium的。

python
from selenium import webdriver from selenium.webdriver.edge.options import Options edge_options = Options() edge_options.add_argument('--ignore-certificate-errors') # 忽略证书错误 driver = webdriver.Edge(executable_path='path_to_edgedriver', options=edge_options) driver.get('https://example.com')

通过以上示例,无论是Chrome、Firefox还是Edge浏览器,我们都可以通过设置各自的配置来接受不受信任的SSL证书,从而确保Selenium可以顺利地访问HTTPS网站,即使它们的SSL证书存在问题。这在测试环境中特别有用,因为测试环境常常使用自签名证书。

2024年8月14日 00:08 回复

你的答案