我的Selenium代码登录到一个网站,然后进入一个页面,该页面带有iframe中存在的按钮。检查chrome中的元素并使用浏览器的控制台,我找到了iframe:
iframe = document.getElementById("deputy-app-view1045")
然后我找到了该元素并能够单击它:
iframe.contentWindow.document.getElementById("csv_download").click()
在我的python代码中,我插入:
browser.execute_script('document.getElementById("deputy-app-view1043").contentWindow.document.getElementById("csv_download").click()')
但是,错误是"TypeError: document.getElementById(...) is null".
:(
[解决方案]弄清楚了!只需在js脚本内添加“ return”!感谢大家!旧版本:
browser.execute_script('document.getElementsByClassName("app-iframe dg-content-box margin-none Report Builder (BETA) ready")[0].contentWindow.document.getElementById("csv_download").href')
固定版本:
browser.execute_script('return document.getElementsByClassName("app-iframe dg-content-box margin-none Report Builder (BETA) ready")[0].contentWindow.document.getElementById("csv_download").href')
由于所需元素在<iframe>
内,因此必须在该元素上调用click()
:
CSS_SELECTOR
:WebDriverWait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it((By.CSS_SELECTOR,"iframe[id^='deputy-app-view']")))
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "#csv_download"))).click()
使用XPATH
:
WebDriverWait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it((By.XPATH,"//iframe[starts-with(@id, 'deputy-app-view')")))
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.ID, "csv_download"))).click()
在这里您可以找到有关Ways to deal with #document under iframe的讨论