我正在尝试加载具有动态HTML的网址。 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()
脚本结果: "接受的条款和条件" "找不到标签"
答案 0 :(得分:2)
实际上,它不仅仅是等待页面加载。
您要查找的元素位于iframe中。在搜索元素之前,您需要切换到它的上下文:
driver.switch_to.frame(0) # 0 here is an index - using 0 since there is only one iframe