Selenium Python:从文件读取并使用单词作为搜索查询时的StaleElementReferenceException

2024-05-15 11:14:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我之前的问题是Selenium Python - Access next pages of search results

在成功地为一个关键字做了这些之后,我需要从一个文件中逐行读取这些关键字,并继续搜索。在

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

url是http://www.nice.org.uk/

^{pr2}$

这将从文件中读取要搜索的关键字,然后将其输入到搜索框中。在

inputElement.submit()

提交查询。这和我之前问的问题差不多,如果str2是静态的,那么一切都会完美地工作,也就是说,我定义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' ;

因为某种原因我得到了这个错误。在

任何帮助将不胜感激!在


Tags: theinpyaccessselenium错误关键字pages
1条回答
网友
1楼 · 发布于 2024-05-15 11:14:36

您的问题是,在执行inputElement.submit()一次之后,页面可能会被刷新,而此时inputElement就会过时。在

我认为在每个inputElement.submit()之后为inputElement获取一个新的引用可以清除它:

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

相关问题 更多 >