【发布时间】:2020-07-10 18:31:08
【问题描述】:
我正在尝试为亚马逊搜索结果创建一个基本的网络爬虫。当我遍历结果时,我有时会到达结果的第 5 页(有时只有第 2 页),然后抛出 StaleElementException。当我在抛出异常后查看浏览器时,我可以看到驱动程序/页面没有向下滚动到页码所在的位置(底部栏)。
我的代码:
driver.get('https://www.amazon.com/s/ref=nb_sb_noss_1?url=search-alias%3Daps&field-keywords=sonicare+toothbrush')
for page in range(1,last_page_number +1):
driver.implicitly_wait(10)
bottom_bar = driver.find_element_by_class_name('pagnCur')
driver.execute_script("arguments[0].scrollIntoView(true);", bottom_bar)
current_page_number = int(driver.find_element_by_class_name('pagnCur').text)
if page == current_page_number:
next_page = driver.find_element_by_xpath('//div[@id="pagn"]/span[@class="pagnLink"]/a[text()="{0}"]'.format(current_page_number+1))
next_page.click()
print('page #',page,': going to next page')
else:
print('page #: ', page,'error')
我看过这个question,我猜可以应用类似的修复,但我不确定如何在页面上找到消失的东西。此外,根据打印语句的发生速度,我可以看到 implicitly_wait(10) 实际上并没有等待整整 10 秒。
异常指向以“driver.execute_script”开头的行。这是一个例外:
StaleElementReferenceException: Message: The element reference of <span class="pagnCur"> is stale; either the element is no longer attached to the DOM, it is not in the current frame context, or the document has been refreshed
有时我会收到 ValueError:
ValueError: invalid literal for int() with base 10: ''
所以这些错误/异常让我相信等待页面完全刷新是有问题的。
【问题讨论】:
-
你的方案是什么?预期输出是什么?
-
一旦你
click(),它会加载一个新页面(带有一个新的 DOM)。所以你的循环的第二次迭代元素已经过时了。
标签: python selenium xpath webdriverwait staleelementreferenceexception