Selenium报错:ERROR: Couldn't read tbsCertificate,添加忽略证书参数仍未解决
解决Selenium证书解析错误及代码问题
首先,你的证书错误核心原因是浏览器选项未被正确应用——你在启动Chrome驱动之后才创建chrome_options,此时设置的参数对已运行的浏览器实例完全无效。此外代码中还有元素定位的错误,以下是完整修正方案:
1. 正确配置并传入浏览器选项
必须在初始化webdriver.Chrome时就将配置好的Options传入,这样证书忽略参数才会生效:
from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.chrome.options import Options from selenium.webdriver.common.by import By # 必须导入By模块 import time start_url = 'https://www.iseecars.com/used-cars/used-tesla-for-sale#Location=66952' + \ '&Radius=all&Make=Tesla&Model=Model+3&Condition=used&_t=a&maxResults=15' + \ '&sort=BestDeal&sortOrder=desc&lfc_t0=MTU2Nzk2NzkzNDc2NQ%3D%3D' # 先配置浏览器选项 chrome_options = Options() chrome_options.add_argument('--allow-running-insecure-content') chrome_options.add_argument('--ignore-certificate-errors') chrome_options.add_argument('--ignore-ssl-errors') # 补充增强忽略SSL错误的参数 # 将选项传入驱动初始化 with webdriver.Chrome(options=chrome_options) as driver: wait = WebDriverWait(driver, 10) driver.get(start_url) # 用显式等待替代sleep,更可靠 teslas = wait.until(lambda d: d.find_element(By.CSS_SELECTOR, 'div#cars_v2-result-list')) # 修正元素定位方式:必须指定定位策略 models = teslas.find_elements(By.TAG_NAME, 'h3') for model in models: print(model.text)
2. 关键问题说明
- 选项未生效:原代码中
chrome_options在driver = webdriver.Chrome()之后创建,浏览器已启动,参数无法被应用,导致证书错误依然存在。 - 元素定位错误:Selenium 4+版本不再支持直接传入选择器字符串作为
find_element参数,必须配合By类指定定位策略(如By.CSS_SELECTOR、By.TAG_NAME等)。 - 参数补充:添加
--ignore-ssl-errors可增强对SSL证书问题的忽略效果,避免部分场景下的解析错误。
3. 优化建议
优先使用显式等待替代time.sleep(),比如等待元素加载完成:
from selenium.webdriver.support import expected_conditions as EC teslas = wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, 'div#cars_v2-result-list')))
这能提高代码稳定性,避免因页面加载慢导致的元素找不到错误。
内容的提问来源于stack exchange,提问作者Stacey
相关产品推荐
相关产品推荐

