Selenium TimeoutException(和 NoSuchElementException),即使在显式等待之后也是如此。奇怪的修复:driver.page_source

Selenium TimeoutException (and NoSuchElementException) even after waiting explicitly. Weird fix: driver.page_source

提问人:Nickstor15 提问时间:10/3/2023 最后编辑:Michael MintzNickstor15 更新时间:10/3/2023 访问量:24

问:

我一直在尝试各种解决方案,以找到未找到的元素,即使在等待之后也是如此。

我最终通过在尝试查找元素之前执行找到了修复程序,这似乎加载了页面并允许找到该元素,但是我不明白为什么会这样。driver.page_source

这是我的原始代码:

driver.find_element('xpath','btn[text()="Next page"]').click()  # push next page button - loads new page 

time.sleep(10)
waiter = WebDriverWait(driver, 30)
waiter.until(EC.visibility_of_element_located((By.XPATH, '//label[text()="Time"]'))) #this returns Timeout Error

我也尝试了后面跟着 ,但无济于事(返回)。time.sleep(30)driver.find_element('xpath','//label[text()="Time"]')NoSuchElementException

如果我运行我的代码并让它等待一分钟才能执行,这将不起作用。但是,如果我自己等待 30 秒,然后在控制台中手动运行,那么它会起作用......driver.find_element('xpath','//label[text()="Time"]')driver.find_element('xpath','//label[text()="Time"]')

在试图弄清楚发生了什么时,我最终找到了一个解决方案:

driver.find_element('xpath','btn[text()="Next page"]').click() # push next page button - loads new page

driver.page_source  # seems to force the page to load?

waiter = WebDriverWait(driver, 10) 
waiter.until(EC.visibility_of_element_located((By.XPATH, '//label[text()="Time"]')))  # no more error

我希望有人能提供一些关于原因的见解:

  1. 在等待时间后手动输入代码(有时)
  2. 在服务员之前执行我的代码可以正常工作driver.page_source
python selenium-webdriver nosuchelementexception 超时异常

评论

0赞 zvz 10/3/2023
你能不能使用原始代码并休眠 10 秒以上,这样你就有时间在浏览器中检查 html 是否存在该元素。

答: 暂无答案