我正在尝试为amazon结果创建一个基本的web scraper。当我迭代结果时,有时会得到结果的第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: invalid literal for int() with base 10: ''
因此,这些错误/异常使我相信,在等待页面完全刷新时会发生一些事情。