使用 selenium python 循环遍历元素时遇到问题

时间:2021-05-30 22:20:06

标签: python selenium loops

我已经查看了 Stackoverflow 的所有内容,试图找到这个问题的答案,但没有找到。我的代码有什么问题是它点击了第一个元素,然后得到了我想要的“href”,但在那之后立即停止,并抛出像

这样的错误
box[x].click()

&

selenium.common.exceptions.StaleElementReferenceException: Message: stale element reference: element is not attached to the page document

这是代码

box = driver.find_elements_by_class_name("info-section.info-primary")

x = 0
#for x in range(0, len(box)):
while True:
    while x <= len(box):
        #if box[x].is_displayed():
        driver.implicitly_wait(2)
        # error is happening here
        box[x].click()
        x += 1
        try:
            website = WebDriverWait(driver, 10).until(
                EC.presence_of_element_located((By.CLASS_NAME, "primary-btn.website-link"))
            )
            print(website.get_attribute('href'))
            driver.back()
        except:
            driver.back()
    if not driver.find_element_by_class_name('ajax-page'):
        break
    else:
        driver.find_element_by_class_name('ajax-page').click()

1 个答案:

答案 0 :(得分:0)

您收到 StaleElementReference 错误是因为您定义了 box,导航到另一个页面,然后再次尝试使用 box 变量。解决这个问题的最快方法是在每个循环中定位没有变量的元素:

box = driver.find_elements_by_class_name("info-section.info-primary")

x = 0
#for x in range(0, len(box)):
while True:
    while x <= len(box):
        #if box[x].is_displayed():
        driver.implicitly_wait(2)
        # error is happening here
        driver.find_elements_by_class_name("info-section.info-primary")[x].click()
        x += 1
        try:
            website = WebDriverWait(driver, 10).until(
                EC.presence_of_element_located((By.CLASS_NAME, "primary-btn.website-link"))
            )
            print(website.get_attribute('href'))
            driver.back()
        except:
            driver.back()
    if not driver.find_element_by_class_name('ajax-page'):
        break
    else:
        driver.find_element_by_class_name('ajax-page').click()