使用 Python 进行迭代时出现 StaleElementException

2024-02-15

我正在尝试为亚马逊结果创建一个基本的网络抓取工具。当我迭代结果时,有时会到达结果的第 5 页(有时仅第 2 页),然后是StaleElementException被抛出。当我在抛出异常后查看浏览器时,我可以看到驱动程序/页面没有向下滚动到页码所在的位置(底部栏)。

My code:

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 https://stackoverflow.com/questions/44373619/staleelementexception-when-clicking-on-a-tablerow-in-an-angular-webpage,我猜测可以应用类似的修复,但我不确定如何在页面上找到消失的内容。另外,根据打印语句发生的速度,我可以看到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: ''

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


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

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秒, but 最多等待 10 秒让元素出现在 HTML DOM 中。因此,如果在 1 或 2 秒内找到元素,则等待完成,您将不会等待 8-9 秒......

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 Python 进行迭代时出现 StaleElementException 的相关文章

随机推荐