【发布时间】:2015-10-28 00:03:28
【问题描述】:
我正在使用 selenium 抓取 this 网站。首先,我点击了景点类型旁边的清除按钮。然后我点击了类别列表底部的更多链接。现在,我通过 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)
【问题讨论】:
-
为什么你的代码中有休眠?这不是你在 webdriver 中等待元素的方式
-
@CoreyGoldberg 所以我应该使用等待吗?
-
您的最新编辑正在吞噬 NoSuchElementException...我怀疑您是否真的想这样做。
-
另外,请发布整个堆栈跟踪,以便我们知道错误来自哪里。并停止编辑您问题中的代码..很难调试移动目标,
-
现在您的代码中有调试(打印)语句和语法错误(缩进)。它与您的原始问题不同。