遍历Web元素时,硒中的陈旧异常

时间:2019-07-22 10:51:03

标签: python selenium

循环浏览推送到列表的Web元素时,由于循环返回页面时不存在DOM,因此获得称为过时异常的异常。

下面是我尝试使用的代码,但是没有完成工作。

elem = driver.find_element(By.XPATH, '//*[@id="wpbody-content"]/div[3]/ul/li[2]/a').click()

# To get the list of web elements
links = driver.find_elements_by_class_name('row-title')


  for i in range(len(links)):
        attempt = 0
        result = False

        # attempting to get the DOM using a while loop (looping back to the previous page)
        while attempt < 2:
            try:
                links[i].click()
                result = True
                break
            except:
                print("stale occured")
            finally:
                attempt += 1

        # If found the DOM continue the execution
        if result == True:
            select = Select(driver.find_element_by_name('pagegoals'))
            select.select_by_value('goal4')

            select = Select(driver.find_element_by_name('pagetype'))
            select.select_by_value('marketing')

            # To execute the script
            driver.execute_script('''
                window.document.querySelector("#publish").click();
            ''')

            # Getting back to the previous page
            driver.execute_script("window.history.go(-1)")

1 个答案:

答案 0 :(得分:0)

后退时使用该页面。页面正在刷新,硒无法识别元素并引发过时错误。

您需要再次重新分配元素。立即尝试。

elem = driver.find_element(By.XPATH, '//*[@id="wpbody-content"]/div[3]/ul/li[2]/a').click()

# To get the list of web elements
links = driver.find_elements_by_class_name('row-title')


for i in range(len(links)):
        attempt = 0
        result = False
        #re-assinge the elements again
        links = driver.find_elements_by_class_name('row-title')
        # attempting to get the DOM using a while loop (looping back to the previous page)
        while attempt < 2:
            try:
                links[i].click()
                result = True
                break
            except:
                print("stale occured")
            finally:
                attempt += 1

        # If found the DOM continue the execution
        if result == True:
            select = Select(driver.find_element_by_name('pagegoals'))
            select.select_by_value('goal4')

            select = Select(driver.find_element_by_name('pagetype'))
            select.select_by_value('marketing')

            # To execute the script
            driver.execute_script('''
                window.document.querySelector("#publish").click();
            ''')

            # Getting back to the previous page
            driver.execute_script("window.history.go(-1)")
相关问题