我使用python和selenium,用firefox驱动程序加载页面。将显示一个链接列表,我可以收集这些链接,但是当我尝试依次单击每个链接时(该链接前进到包含我抓取的数据的页面),然后返回到带有链接列表的上一页并单击下一个,将引发Stale Element Exception。已经看了10多个视频,阅读了20多个有关应该如何解决此问题的帖子,尝试了多种选择都无效。
这是我的代码。
links = driver.find_elements_by_partial_link_text('2019 TRC')
for link in links:
link.click()
get_data() #this gathers data on the new page appearing after clicking the link
driver.back() #this travels back to page with link list, but then fails with stale element exception
我的目的是将链接收集到一个列表中,在列表上单击并单击每个链接(这将打开一个包含数据的新页面),以迭代该列表,收集数据,返回包含链接的页面,单击下一个链接,直到链接列表已用完。
我尝试了所有这些选项,但都失败了。
#1
# for case in links:
# try:
# case.click()
# except StaleElementReferenceException:
# links = driver.find_elements_by_xpath("//*[contains(text(), '2019 TRC')]")
# case.click()
# driver.back()
#2
# for case in links:
# try:
# case.click()
# except StaleElementReferenceException:
# driver.find_elements_by_xpath("//*[contains(text(), '2019 TRC')]")
# case.click()
# driver.back()
#3 - This just keeps going back after returning to case list page
# for case in links:
# try:
# case.click()
# except StaleElementReferenceException:
# driver.find_elements_by_xpath("//*[contains(text(), '2019 TRC')]")
# time.sleep(1)
# driver.back()
#4 Stays at the link list page
# for case in links:
# try:
# case.click()
# except StaleElementReferenceException:
# driver.find_elements_by_xpath("//*[contains(text(), '2019 TRC')]")
# case.click()
# time.sleep(1)
# driver.back()
#5 stays at the link list page
# for case in links:
# try:
# case.click()
# except StaleElementReferenceException:
# links = driver.find_elements_by_xpath("//*[contains(text(), '2019 TRC')]")
# case.click()
# time.sleep(1)
# driver.back()
#6 Changed elements to element (single) and this stays as the link list page again
# for case in links:
# try:
# case.click()
# except StaleElementReferenceException:
# driver.find_element_by_xpath("//*[contains(text(), '2019 TRC')]")
# case.click()
# time.sleep(1)
# driver.back()
#7 Stayed on the first case detail page
#
# for case in links:
# try:
# case.click()
# except StaleElementReferenceException:
# driver.find_element_by_xpath("//*[contains(text(), '2019 TRC')]")
# case.click()
# driver.back()
#8 DId not work using links= instead of just the driver.
# for case in links:
# try:
# case.click()
# except StaleElementReferenceException:
# links = driver.find_element_by_xpath("//*[contains(text(), '2019 TRC')]")
# case.click()
# driver.back()
我什至尝试查找带有“ by_partial_link_text”或“ by_id”的链接,并且仍然存在相同的错误表面。
如果您迅速将此问题标记为已回答,请注意,我刚才已经阅读了Stackoverflow上的其他文章,但没有一个提供有效的解决方案。我尝试了其中大约五个。