使用Python+Selenium爬取网站时出现err_http2_protocol_error错误求助
解决Selenium点击搜索按钮出现ERR_HTTP2_PROTOCOL_ERROR的方案
以下是针对你遇到问题的具体解决步骤:
1. 匹配ChromeDriver与Chrome版本
ChromeDriver版本必须和本地Chrome浏览器严格对应,版本不兼容是触发协议错误的常见原因:
- 打开Chrome,通过「菜单→帮助→关于Google Chrome」查看浏览器版本
- 下载同大版本的ChromeDriver替换现有驱动
2. 强制禁用HTTP/2协议
手动访问正常但Selenium触发错误,大概率是驱动默认的HTTP/2配置和网站不兼容,强制切换到HTTP/1.1:
修改代码如下:
from selenium.webdriver import Chrome, ChromeOptions from selenium.webdriver.common.by import By options = ChromeOptions() # 禁用HTTP/2协议 options.add_argument('--disable-http2') # 模拟正常浏览器的User-Agent options.add_argument('--user-agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36"') driver = Chrome(options=options) url = "https://web.trf3.jus.br/consultas/internet/consultareqpag" driver.get(url) # 手动完成验证码 # 隐式等待10秒,确保元素加载完成 driver.implicitly_wait(10) driver.find_element(By.ID, "CpfCnpj").send_keys('05325542000158') driver.find_element(By.ID, "pesquisar").click()
3. 添加显式等待逻辑
避免因元素未完全就绪就点击导致的异常,用显式等待确保元素可交互:
from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC # 手动完成验证码后 wait = WebDriverWait(driver, 15) # 等待输入框可点击 cpf_input = wait.until(EC.element_to_be_clickable((By.ID, "CpfCnpj"))) cpf_input.send_keys('05325542000158') # 等待搜索按钮可点击后再点击 search_btn = wait.until(EC.element_to_be_clickable((By.ID, "pesquisar"))) search_btn.click()
4. 绕过基础自动化检测
部分网站会识别Selenium的特征,添加参数隐藏自动化标识:
在ChromeOptions中追加以下配置:
options.add_argument('--disable-blink-features=AutomationControlled') options.add_experimental_option("excludeSwitches", ["enable-automation"]) options.add_experimental_option('useAutomationExtension', False)
5. 检查网络环境
确保Selenium使用的网络和手动访问一致,关闭代理、VPN等可能干扰HTTP协议的工具后重试。
内容的提问来源于stack exchange,提问作者Juliano Hausen Oliveira da Cos
相关产品推荐
相关产品推荐

