【发布时间】: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