Python Selenium:WebDriverWait,尽管加载仍未找到元素
Python Selenium: WebDriverWait, element not found despite loading
我正在尝试加载具有动态 HTML 的 URL。 selenium webdriver 加载 URL 正常,但它似乎在 HTML 完全呈现之前搜索元素。我试过 WebDriverWait,但似乎不起作用。
有趣的是,selenium找不到元素后,我可以手动使用Chrome开发者工具成功找到元素。
有什么想法吗?
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
chromepath = "C:\Program Files (x86)\Google\Chrome\Application\chromedriver.exe"
url = "https://www.msci.com/end-of-day-data-search"
delay = 15 #seconds
br = webdriver.Chrome(chromepath)
br.get(url)
try:
br.find_element_by_class_name("accept-btn").click()
print("accepted terms and conditions")
finally:
try:
labelxpath = "//*[@id='form-content']/table[1]/tbody/tr[2]/td/span"
labelElement = WebDriverWait(br, delay).until(lambda br: br.find_element_by_xpath(labelxpath))
print(labelElement)
except:
print("could not find label")
br.close()
脚本结果:
"accepted terms and conditions"
"could not find label"
其实,不仅仅是等待页面加载。
您要查找的元素在 iframe 中。在搜索元素之前,您需要切换到它的上下文:
driver.switch_to.frame(0) # 0 here is an index - using 0 since there is only one iframe
我正在尝试加载具有动态 HTML 的 URL。 selenium webdriver 加载 URL 正常,但它似乎在 HTML 完全呈现之前搜索元素。我试过 WebDriverWait,但似乎不起作用。
有趣的是,selenium找不到元素后,我可以手动使用Chrome开发者工具成功找到元素。
有什么想法吗?
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
chromepath = "C:\Program Files (x86)\Google\Chrome\Application\chromedriver.exe"
url = "https://www.msci.com/end-of-day-data-search"
delay = 15 #seconds
br = webdriver.Chrome(chromepath)
br.get(url)
try:
br.find_element_by_class_name("accept-btn").click()
print("accepted terms and conditions")
finally:
try:
labelxpath = "//*[@id='form-content']/table[1]/tbody/tr[2]/td/span"
labelElement = WebDriverWait(br, delay).until(lambda br: br.find_element_by_xpath(labelxpath))
print(labelElement)
except:
print("could not find label")
br.close()
脚本结果: "accepted terms and conditions" "could not find label"
其实,不仅仅是等待页面加载。
您要查找的元素在 iframe 中。在搜索元素之前,您需要切换到它的上下文:
driver.switch_to.frame(0) # 0 here is an index - using 0 since there is only one iframe