Selenium函数在单击之前检查新鲜度,以避免陈旧元素异常

问题描述

我正在从使用jquery的网站上抓取数据,有时会收到Stale Element异常,该异常已通过在try / except之间引入睡眠来解决

但是,我想使其更健壮,并且在浏览文档时:https://selenium-python.readthedocs.io/waits.html#explicit-waits我发现有一种方法可以使用“ staleness_of”方法检查元素是否陈旧。

webdriverwait(driver,10).until(EC.staleness_of(driver.find_element_by_link_text("2020:")))

但是似乎上面的语句等待元素过期,这与我要查找的相反,即是否有一种方法可以等待元素不再过期然后继续操作(如果可能,请单击它)?

测试代码,我尝试在其中替换sleep()

from time import sleep

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

driver = webdriver.Chrome()
driver.implicitly_wait(15)
driver.get('https://vahan.parivahan.gov.in/vahan4dashboard/')

driver.find_element_by_xpath('//*[@id="j_idt45"]').click() # Click Refresh

try:
    webdriverwait(driver,10).until(EC.element_to_be_clickable((By.LINK_TEXT,'2020:'))).click()
except Exception as e:
    print("Exception occoured!",e)
    sleep(5) # <============ Tying to replace this ============<
    try:
        webdriverwait(driver,'2020:'))).click()
    except:
        input("Year selection Failed")
sleep(2) # <============ Tying to replace this ============<

text_string = driver.find_element_by_xpath('//*[@id="t3"]/div').text

解决方法

我不是Python本地开发人员,但是,我在C#中以:-

处理
public static void StaleEnterTextExceptionHandler(this IWebDriver driver,By element,string value)
        {
            try
            {
                driver.EnterText(element,value);
            }
            catch (Exception e)
            {
                if (e.GetBaseException().Equals(typeof(StaleElementReferenceException)))
                {
                    StaleEnterTextExceptionHandler(driver,element,value);
                }
                else
                throw e;
            }
        }

除非陈旧的异常不存在,否则逻辑只是简单地递归调用该方法。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...