【问题标题】:selenium - waiting for item to load (stale element reference error)selenium - 等待项目加载(过时元素引用错误)
【发布时间】:2019-03-20 22:03:19
【问题描述】:

我正在执行一个脚本,该脚本单击多个页面以检索数据。每次点击后,新页面显然要加载,加载时间差别很大(大多为 2-3 秒,有时 > 20 秒)。因此,我需要使代码灵活地等待执行,直到元素被加载。我已经实现了下面的解决方案,但我仍然得到一个陈旧的元素引用错误,我不明白(因为代码在加载完成之前不应退出 while 循环)。谁能解释为什么会发生这种情况/我可以做些什么来解决?

抱歉,我无法与您共享可执行脚本。

error = 1 
if page_ref < Max_pagenum_1: 
    while error == 1: 
        try: 
            link = browser.find_element_by_xpath('//li[contains(@class,"page-item") and contains(@class,"active")]/following-sibling::li/a').click()
            error = 0
            time.sleep(3)
        except: 
            error = 1
            time.sleep(20)
        else: 
            print('finished' + Name) 

【问题讨论】:

  • 用您的相关HTML代码试验错误堆栈跟踪(如果有的话)更新问题

标签: python selenium web-scraping


【解决方案1】:

您可以使用等待语句。大致如下:

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

error = 1 
if page_ref < Max_pagenum_1: 
    while error == 1: 
        try:
            WebDriverWait(browser, 20).until(
        EC.presence_of_element_located((By.XPATH, '//li[contains(@class,"page-item") and contains(@class,"active")]/following-sibling::li/a')))

            link = browser.find_element_by_xpath('//li[contains(@class,"page-item") and contains(@class,"active")]/following-sibling::li/a').click()
            error = 0
            time.sleep(3)
        except: 
            error = 1
            time.sleep(20)
        else: 
            print('finished' + Name) 

【讨论】:

  • 有效!感谢您的帮助@Lafa
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-05
  • 1970-01-01
  • 1970-01-01
  • 2023-03-30
  • 1970-01-01
  • 2012-06-14
相关资源
最近更新 更多