用webdriver做UI自动化,运行到点击搜索时报错,检查不出问题,大家看一下,遇到过这种情况怎么解决

用webdriver做UI自动化,运行到点击搜索时报错,检查不出问题,大家看一下,遇到过这种情况怎么解决

错误信息:
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"css selector","selector":"[id="searchBtn"]"}
(Session info: chrome=89.0.4389.90)

程序:

driver.find_element_by_id("searchBtn").click() 点击搜索 --------报错行----------

sleep(3)
driver.quit()

报错信息:

Traceback (most recent call last):
File "D:/软件安装/pycharm/和包2.0/UI/demo1.py", line 26, in
driver.find_element_by_id("searchBtn").click()

selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"css selector","selector":"[id="searchBtn"]"}
(Session info: chrome=89.0.4389.90)

元素未找到,一般可能的原因有两个:
元素定位错了——>解决方式,找到正确的元素定位,重新尝试
页面元素还未加载出来,就执行了点击操作;——>可以在点击之前加个等待,等待元素加载出来再点击搜索

如果不对搜索按钮进行校验,单纯想要执行搜索操作,也可以向输入框发送键盘事件Enter,一般输入框都会支持enter搜索的

你确认下页面上确实有id是searchBtn的元素吗?

页面加载后有等待2秒后再点击搜索的,是不是这个页面下的按钮不能直接定位呢