【问题标题】:Selenium function to check for freshness before click to avoid stale element exception [duplicate]Selenium 功能在单击之前检查新鲜度以避免陈旧元素异常[重复]
【发布时间】:2020-09-06 07:24:30
【问题描述】:

我正在从一个使用 jquery 的站点上抓取数据,有时我会遇到过时元素异常,我通过在 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, 10).until(EC.element_to_be_clickable((By.LINK_TEXT,'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 selenium selenium-webdriver exception staleelementreferenceexception


    【解决方案1】:

    我不是本地 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;
                }
            }
    

    除非不存在过时的异常,否则逻辑只是递归调用该方法。

    【讨论】:

      猜你喜欢
      • 2017-05-28
      • 1970-01-01
      • 2021-03-13
      • 1970-01-01
      • 2023-04-04
      • 1970-01-01
      • 2014-02-24
      • 2021-10-02
      • 1970-01-01
      相关资源
      最近更新 更多