Python Selenium on click站点返回到类似状态并出现陈旧错误

Python Selenium on click站点返回到类似状态并出现陈旧错误,python,selenium,Python,Selenium,我正在使用selenium清理网站。首先,我点击了吸引类型旁边的清除按钮。然后我点击了分类列表底部的“更多”链接。现在,对于每个元素,我按id查找元素并单击链接。问题是,当我点击第一类户外活动时,网站再次回到初始状态,当我尝试点击下一个链接时,出现以下错误: StaleElementReferenceException: Message: Element is no longer attached to the DOM 我的代码是: class TripSpider(CrawlSpider):

我正在使用selenium清理网站。首先,我点击了吸引类型旁边的清除按钮。然后我点击了分类列表底部的“更多”链接。现在,对于每个元素,我按id查找元素并单击链接。问题是,当我点击第一类户外活动时,网站再次回到初始状态,当我尝试点击下一个链接时,出现以下错误:

StaleElementReferenceException: Message: Element is no longer attached to the DOM
我的代码是:

class TripSpider(CrawlSpider):
  name = "tspider"
  allowed_domains = ["tripadvisor.ca"]
  start_urls = ['http://www.tripadvisor.ca/Attractions-g147288-Activities-c42-Dominican_Republic.html']

  def __init__(self):
    self.driver = webdriver.Firefox()
    self.driver.maximize_window()


  def parse(self, response):
    self.driver.get(response.url)
    self.driver.find_element_by_class_name('filter_clear').click()
    time.sleep(3)
    self.driver.find_element_by_class_name('show').click()
    time.sleep(3)
    #to handle popups
    self.driver.switch_to.window(browser.window_handles[-1])
    # Close the new window
    self.driver.close()
    # Switch back to original browser (first window)
    self.driver.switch_to.window(browser.window_handles[0])
    divs = self.driver.find_elements_by_xpath('//div[contains(@id,"ATTR_CATEGORY")]')
    for d in divs:
      d.find_element_by_tag_name('a').click()
      time.sleep(3)

这个网站的问题是,每次你点击一个元素,DOM都会发生变化,所以你不能循环浏览过时的元素

不久前我也遇到了同样的问题,我为每个链接使用不同的窗口解决了这个问题

您可以更改这部分代码:

divs = self.driver.find_elements_by_xpath('//div[contains(@id,"ATTR_CATEGORY")]')
for d in divs:
    d.find_element_by_tag_name('a').click()
    time.sleep(3)
用于:


为什么代码中有睡眠?这不是你等待元素的方式webdriver@CoreyGoldberg那么我应该使用waits吗?您最近的编辑正在吞咽NoTouchElementException。。。我怀疑你真的想这么做。另外,请张贴整个stacktrace,以便我们知道错误来自何处。并停止编辑问题中的代码。。调试移动目标很困难,现在代码中有调试(打印)语句和语法错误(缩进)。这与您原来的问题不同。我尝试了shift+enter甚至ctrl+enter技术,但即使在正常情况下,它也会在同一页面中更新,而不是在新窗口中打开。您是否将其他注释中的隐式等待与此方法相结合?我不明白为什么它甚至不打开一个新窗口。。。
from selenium.webdriver.common.keys import Keys
mainWindow = self.driver.current_window_handle
divs = self.driver.find_elements_by_xpath('//div[contains(@id,"ATTR_CATEGORY")]')
for d in divs:
    # Open the element in a new Window
    d.find_element_by_tag_name('a').send_keys(Keys.SHIFT + Keys.ENTER)
    self.driver.switch_to_window(self.driver.window_handles[1])

    # Here you do whatever you want in the new window

    # Close the window and continue
    self.driver.find_element_by_tag_name('body').send_keys(Keys.CONTROL + 'w')
    self.driver.switch_to_window(mainWindow)