如何使用Selenium(Ruby)获取SSL证书信息?
Absolutely! While Selenium doesn’t have out-of-the-box methods to grab SSL certificate details or check for mixed content, you can use the Chrome DevTools Protocol (CDP) right through your Ruby Selenium setup to get this info. Here’s how to tweak your code to capture those details:
1. Fetch SSL Certificate Details (Issuer, Expiration Date)
Chrome’s DevTools let you retrieve the SSL certificate for the current origin using the Security.getCertificate command. You’ll need to enable the Security domain first, then extract and parse the certificate data:
2. Check for Mixed Content
Use the Security.getMixedContentStatus command to detect if the page loads any insecure resources over HTTP while using HTTPS.
Here’s the full modified code:
require 'selenium-webdriver' require 'time' options = Selenium::WebDriver::Chrome::Options.new(args: ['headless']) driver = Selenium::WebDriver.for(:chrome, options: options) # Enable the Security domain to access CDP security-related commands driver.execute_cdp('Security.enable') driver.get 'https://stackoverflow.com/' # Fetch and parse SSL certificate information origin = driver.current_url.match(%r{^https?://[^/]+})[0] certificate_data = driver.execute_cdp('Security.getCertificate', origin: origin)['certificate'] issuer = certificate_data['issuer'] valid_from = Time.at(certificate_data['validFrom'] / 1000).utc valid_to = Time.at(certificate_data['validTo'] / 1000).utc puts "SSL Certificate Issuer: #{issuer}" puts "Valid From: #{valid_from}" puts "Valid Until: #{valid_to}" # Check for mixed content mixed_content_result = driver.execute_cdp('Security.getMixedContentStatus') puts "\nMixed Content Status: #{mixed_content_result['mixedContentStatus']}" if mixed_content_result['resources'].any? puts "Mixed Content Resources:" mixed_content_result['resources'].each do |resource| puts "- #{resource['url']} (#{resource['type']})" end end driver.quit
Key Notes:
- The
Security.enablecall is necessary to activate the DevTools Security domain before running related commands. - Certificate timestamps are returned as epoch milliseconds, so we convert them to human-readable
Timeobjects using Ruby’sTime.at. - The mixed content status will return
noneif no insecure resources are loaded, ordisplayed/downloadedif there are mixed content issues, along with a list of the problematic resources.
This approach works specifically with Chrome (since it uses CDP), which aligns with your current setup.
内容的提问来源于stack exchange,提问作者Shobhit

