Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/318.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python元素异常_Python_Selenium_Staleelementreferenceexception_Staleobjectstateexception_Selenium Webdriver Python - Fatal编程技术网

Python元素异常

Python元素异常,python,selenium,staleelementreferenceexception,staleobjectstateexception,selenium-webdriver-python,Python,Selenium,Staleelementreferenceexception,Staleobjectstateexception,Selenium Webdriver Python,我正在寻找一种解决StaleElementReferenceException的方法,该方法在使用Selenium导航回上一页时出现 下面是重现错误的示例代码: from selenium.webdriver import Chrome from selenium.common.exceptions import NoSuchElementException browser = Chrome() browser.get('https://stackoverflow.com/questions/'

我正在寻找一种解决StaleElementReferenceException的方法,该方法在使用Selenium导航回上一页时出现

下面是重现错误的示例代码:

from selenium.webdriver import Chrome
from selenium.common.exceptions import NoSuchElementException
browser = Chrome()
browser.get('https://stackoverflow.com/questions/')

# Closing the pop-up for cookies
try:    
    browser.find_element_by_class_name('js-accept-cookies').click()
except NoSuchElementException:
    pass

# Getting list of links on a StackOverflow page
links = browser.find_element_by_id('questions').find_elements_by_tag_name('a')


links[0].click()

# Going back

browser.back()
try:    
    browser.find_element_by_class_name('js-accept-cookies').click()
except NoSuchElementException:
    pass

# Using the old links
links[1].click()
我从类似的问题中理解了根本原因

但是,由于性能原因,建议的解决方案(即每次我返回时重新蚀刻链接)不适合我

还有别的选择吗

例如,强制在新选项卡中打开新页面,以便我可以在两个选项卡之间导航

任何其他解决方案都将不胜感激

links =[ x.get_attribute('href') for x in driver.find_element_by_id('questions').find_elements_by_tag_name('a')]
driver.get(links[0])
driver.back()

只需获取href值并像这样来回移动即可。页面移动时,您从页面中获取的元素会丢失。

它工作得非常好!谢谢没问题,请投票,如果有帮助,请接受我的回答。