gpt4 book ai didi

python - 使用 Python 迭代时出现 StaleElementException

转载 作者:行者123 更新时间:2023-11-28 21:34:14 25 4
gpt4 key购买 nike

我正在尝试为亚马逊搜索结果创建一个基本的网络抓取工具。当我遍历结果时,有时会到达结果的第 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”开头的行。这是异常(exception)情况:

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: ''

所以这些错误/异常让我相信在等待页面完全刷新时发生了一些事情。

最佳答案

如果您只想让您的脚本遍历所有结果页面,则不需要任何复杂的逻辑 - 只需在可能的情况下单击“下一步”按钮即可:

from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait as wait
from selenium.common.exceptions import TimeoutException

driver = webdriver.Chrome()

driver.get('https://www.amazon.com/s/ref=nb_sb_noss_1?url=search-alias%3Daps&field-keywords=sonicare+toothbrush')

while True:
try:
wait(driver, 10).until(EC.element_to_be_clickable((By.CSS_SELECTOR, 'a > span#pagnNextString'))).click()
except TimeoutException:
break

附言另请注意,implicitly_wait(10) 不应等待整整 10 秒,而是最多等待 10 秒以使元素出现在 HTML DOM 中。因此,如果在 1 或 2 秒内找到元素,则等待完成,您将不会等待休息 8-9 秒...

关于python - 使用 Python 迭代时出现 StaleElementException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53640973/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com