Selenium向文本框发送回车报unexpected command response错误
Selenium 回车触发搜索时抛出加载状态未知异常的解决方法
问题表现
执行搜索功能时代码逻辑实际生效,页面可以正常跳转到搜索结果页,但运行到search.send_keys(Keys.ENTER)行时抛出异常终止程序,核心报错信息如下:
selenium.common.exceptions.WebDriverException: Message: unknown error: cannot determine loading status from unknown error: unexpected command response (Session info: chrome=103.0.5060.66)
问题复现的完整代码:
from selenium import webdriver from selenium.webdriver.chrome.service import Service from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.by import By import time PATH="C:\Program Files (x86)\chromedriver.exe" s=Service(PATH) driver = webdriver.Chrome(service=s) url='https://www.techwithtim.net/' driver.get(url) print(driver.title) search=driver.find_element(by=By.NAME, value="s") search.send_keys("test") search.send_keys(Keys.ENTER) time.sleep(5) driver.close()
故障原因
该问题是Chrome 103版本与4.3.0以下版本Selenium的已知兼容性缺陷:当通过发送回车键指令触发页面跳转时,ChromeDriver无法正确解析页面加载完成的响应信号,判定命令执行失败抛出异常,但实际按键操作已经生效,页面跳转逻辑正常执行。
修复方案
- 方案一(推荐):升级Selenium到4.3.0及以上版本,官方已在该版本修复此兼容性问题,执行以下命令完成升级:
pip install --upgrade selenium - 方案二:不修改Selenium版本,替换回车提交逻辑为点击搜索按钮提交,规避触发该兼容bug,将原代码中
search.send_keys(Keys.ENTER)替换为以下内容即可:
# 定位搜索提交按钮并点击 search_submit = driver.find_element(By.ID, "searchsubmit") search_submit.click()
- 方案三(临时兼容):直接捕获对应异常跳过即可,因操作本身已经执行成功,捕获异常不会影响后续自动化流程运行,代码示例:
from selenium.common.exceptions import WebDriverException search.send_keys("test") try: search.send_keys(Keys.ENTER) except WebDriverException: # 跳过Chrome 103版本已知的加载状态识别异常 pass
内容的提问来源于stack exchange,提问作者simonkerike
相关产品推荐
相关产品推荐

