首页 > 解决方案 > 如何使用 selenium python 获取网站 SSL 证书到期、颁发者等的详细信息?

问题描述

我想获取在 chrome 浏览器中看到的网页的证书详细信息。详情如:

在此处输入图像描述

我不确定如何继续或在哪里寻找证书。我试图在网络请求中查找相同的内容,但我认为证书详细信息未存储在网络请求中。我尝试了以下代码:

from seleniumwire import webdriver
import pytest
from selenium.webdriver.chrome.options import Options
import time
import allure

class Test_main():

    @pytest.fixture()
    def test_setup(self):
        # initiating browser
        chrome_options = Options()
        chrome_options.binary_location=\
            r"C:\Users\libin.thomas\AppData\Local\Google\Chrome\Application\chrome.exe"
        chrome_options.add_argument('--start-maximized')
        chrome_options.add_argument('--headless')

        self.driver = webdriver.Chrome(executable_path=r"D:/Python/Sel_python/drivers/chromedriverv86/chromedriver.exe",options=chrome_options)
       

        # terminate script
        yield
        self.driver.close()
        self.driver.quit()
        print("Test completed")

    @allure.severity(allure.severity_level.BLOCKER)
    def testcase_01(self, test_setup):
        self.driver.get("https://lifesciences.cactusglobal.com/")
        title = self.driver.title
        print("Page title: "+title)

        #Capturing network requests
        for request in self.driver.requests:
            if request.response:
              print(
                  request.url,
                  request.response.status_code,
                  request.response.headers
              )

无论如何我可以使用 selenium 或任何 Pypi 包获取 SSL 证书的详细信息吗?

标签: pythonseleniumsslselenium-webdriver

解决方案


使用 selenium 可能无法获取这些信息,因为使用 Javascript 从浏览器内部获取这些信息是不可能的。可以尝试直接使用一些 Python 代码访问该网站:

import ssl
 
conn = ssl.create_connection(('google.com',443))
ctx = ssl.create_default_context() 
conn = ctx.wrap_socket(conn, server_hostname = 'google.com')
print(conn.getpeercert())

getpeercert返回的字典包含有关颁发者和有效性的所有必要信息。

请注意,尽管 Python 和浏览器(以及 selenium)直接访问的行为略有不同,因为使用了不同的 TLS 堆栈和/或有关密码、支持的 TLS 版本等的不同设置。在某些情况下,这会导致 Python 代码出现 TLS 握手问题,而浏览器不会发生这种问题。

还有一些情况是服务器中的证书设置不正确,链证书丢失。浏览器通常会成功地解决这个问题,Python 不会。在这种情况下,上面的代码也会失败,可能需要使用更复杂的代码,请参阅Python 使用 ssl.getpeercert() 从 URL 获取通用名称


推荐阅读