Selenium Python:读取文件时使用单词作为搜索查询导致StaleElementReferenceException

1 投票
1 回答
2667 浏览
提问于 2025-04-18 09:29

我之前的问题是 Selenium Python - 访问搜索结果的下一页

在成功处理一个关键词后,我需要从一个文件中逐行读取这些关键词,然后继续搜索。

file1 = open("M:/Users/Cyborg/Desktop/Py/read.txt","r")

这个网址是 http://www.nice.org.uk/

driver.switch_to_default_content()
str2 = file1.readline()
inputElement = driver.find_element_by_name("searchText")
inputElement.clear()
inputElement.send_keys(str2)

这段代码是从文件中读取要搜索的关键词,然后把它输入到搜索框里。

inputElement.submit()

接着提交查询。这和我之前问的问题差不多,如果我把 str2='abc' 定义为静态的,那一切都能正常工作。但是一旦我尝试从文件中读取并继续搜索,就会出现这个错误。

File "M:\Users\Cyborg\Desktop\Py\test.py", line 22, in <module>
    inputElement.submit()
  .
  .
  .
  .

 raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.StaleElementReferenceException: Message: 'Element not found in the cache - perhaps the page has changed since it was looked up' ;

不知为什么我会遇到这个错误。

如果有人能帮忙,我将非常感激!

1 个回答

0

你的问题是,当你执行一次 inputElement.submit() 后,页面可能会刷新,这时候 inputElement 就变得不再有效了。

我觉得在每次执行 inputElement.submit() 后,重新获取一个新的 inputElement 引用就能解决这个问题:

inputElement.submit()
inputElement = driver.find_element_by_name("searchText")

撰写回答