selenium https 跳过校验
时间: 2023-07-19 14:28:25 浏览: 30
为了避免在使用 Selenium 进行 https 访问时出现证书校验的问题,可以按照以下步骤进行设置:
1. 安装 pyopenssl 库和 cryptography 库,可以通过以下命令安装:
```
pip install pyopenssl
pip install cryptography
```
2. 导入 ssl 模块,并添加如下代码:
```
import ssl
from selenium import webdriver
# 忽略证书错误
ssl._create_default_https_context = ssl._create_unverified_context
options = webdriver.ChromeOptions()
options.add_argument('--ignore-certificate-errors')
driver = webdriver.Chrome(chrome_options=options)
```
以上代码中,我们使用 ssl._create_unverified_context() 方法创建了一个不验证证书的 SSLContext,然后将其赋值给了 ssl._create_default_https_context,这样就可以避免 SSL 验证的问题了。同时,我们也在 ChromeOptions 中添加了一个忽略证书错误的参数。
相关问题
selenium 用例跳过
在编写 Selenium 用例时,有时候需要跳过某些测试用例,这时可以使用 Python 中的 `unittest` 模块提供的 `skip` 方法来实现跳过用例。
示例代码:
```python
import unittest
from selenium import webdriver
class TestSelenium(unittest.TestCase):
def setUp(self):
self.driver = webdriver.Chrome()
def tearDown(self):
self.driver.quit()
@unittest.skip("跳过此用例")
def test_case1(self):
self.driver.get("https://www.baidu.com")
self.assertIn("百度", self.driver.title)
def test_case2(self):
self.driver.get("https://www.google.com")
self.assertIn("Google", self.driver.title)
if __name__ == '__main__':
unittest.main()
```
在上面的代码中,我们使用 `@unittest.skip("跳过此用例")` 装饰器来标记需要跳过的测试用例。
执行上面的代码时,会输出以下结果:
```
skipped '跳过此用例'
.
----------------------------------------------------------------------
Ran 2 tests in 6.219s
OK (skipped=1)
```
从结果可以看出,第一个测试用例被跳过了,第二个测试用例正常执行。
selenium跳过图片加载
要使用Selenium跳过图片加载,可以通过设置ChromeOptions来实现。以下是具体的代码实现示例:
引用:
```python
from selenium import webdriver
# 实例化ChromeOptions
options = webdriver.ChromeOptions()
# 禁用图片加载
prefs = {"profile.managed_default_content_settings.images": 2}
options.add_experimental_option("prefs", prefs)
# 启动Chrome浏览器并加载设置
driver = webdriver.Chrome(chrome_options=options)
```
通过以上代码,我们创建了一个ChromeOptions对象,并将图片加载设置为禁用。然后,我们使用该选项启动了Chrome浏览器。
另外,还可以使用Selenium的webdriver的`set_preference()`方法来设置Firefox浏览器跳过图片加载。以下是具体的代码实现示例:
引用:
```python
from selenium import webdriver
# 实例化FirefoxOptions
options = webdriver.FirefoxOptions()
# 禁用图片加载
options.set_preference("permissions.default.image", 2)
# 启动Firefox浏览器并加载设置
driver = webdriver.Firefox(options=options)
```
以上代码中,我们创建了一个FirefoxOptions对象,并使用`set_preference()`方法将图片加载设置为禁用。然后,我们使用该选项启动了Firefox浏览器。
请注意,以上代码只是设置了跳过图片加载的功能,具体的业务逻辑和页面导航等操作需要根据实际需求进行编写。