【问题标题】:having trouble looping through elements with selenium python使用 selenium python 循环遍历元素时遇到问题
【发布时间】:2021-05-30 22:20:06
【问题描述】:

我查看了整个 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()

【问题讨论】:

  • 看起来点击重定向到另一个页面。如果是这样,无论何时调用driver.back(),您都应该等待页面再次加载,然后才能访问该元素。
  • 您确定driver.implicitly_wait(2) 正在等待足够的时间来加载上一页吗?

标签: python selenium loops


【解决方案1】:

您收到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()

【讨论】:

  • 该死,就这么简单,谢谢你解决了我这几天一直在处理的问题。非常感谢布罗迪,希望你有一个美好的一天!干杯
  • 你知道为什么我转到第二页时会弹出同样的错误吗?它说新代码有错误。 while True: while x &lt;= 1: # error is here driver.find_elements_by_class_name("info-section.info-primary")[x].click() x += 1 try: website = driver.find_elemet_by_class_name("primary-btn.website-link") driver.back() except: driver.back() if driver.find_element_by_class_name('next.ajax-page'): next.click() x = 0 else: break
  • 这里有一个错字driver.find_elemet_by_class_name("primary-btn.website-link") -- elemet => `element
  • 我的错误是我试图压缩我的代码以适应这里,我没有那么多使用堆栈
  • 但是你知道为什么转到下一页时它不起作用吗?错误在这里driver.find_elements_by_class_name("info-section.info-primary")[x].click()
猜你喜欢
  • 2021-11-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-12
  • 1970-01-01
相关资源
最近更新 更多