python证书有用吗_python – 如何使用Selenium处理证书?

对于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 documentation,将acceptSslCerts能力设置为True应该适用于所有浏览器,因为它是一个通用的读/写能力:

acceptSslCerts

boolean

Whether the session should accept all SSL certs

by default.

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()

使用Selenium进行自动化测试时,有时会遇到警报框(Alert)弹出的情况。对于这种情况,我们可以使用Selenium的switch_to.alert()方法来切换到警报框并进行操作。然而,由于警报框通常会遮挡页面内容,因此在进行截图时可能无法正确地截取页面内容。 为解决这个问题,可以尝试以下几种方法: 1. 利用JS代码关闭警报框 在Selenium中,我们可以使用execute_script()方法来执行JavaScript代码。因此,如果警报框不是必须要处理的,我们可以通过JS代码来关闭它,然后再进行截图。 示例代码: ```python alert = driver.switch_to.alert alert.dismiss() # 关闭警报框 # 进行截图 driver.save_screenshot('screenshot.png') ``` 2. 使用Pillow库对截图进行修剪 Pillow是Python中一个强大的图像处理库,我们可以使用它对截图进行修剪,只保留我们需要的部分。具体操作如下: ```python from PIL import Image # 获取页面大小 width = driver.execute_script("return document.documentElement.scrollWidth") height = driver.execute_script("return document.documentElement.scrollHeight") # 进行截图 screenshot = driver.get_screenshot_as_png() image = Image.open(BytesIO(screenshot)) # 修剪截图 left = 0 top = 0 right = width bottom = height - 100 # 剔除警报框的高度 image = image.crop((left, top, right, bottom)) # 保存截图 image.save('screenshot.png') ``` 通过以上两种方法,我们可以在Selenium中正确地截取页面内容,避免了警报框对截图的影响。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值