已解决Selenium:Console js代码正常工作,但python>TypeError:document.getElementById(…)单击iframe中的元素时出现null错误

2024-04-26 14:16:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我的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')

Tags: csv代码browserapp元素executereturndownload
1条回答
网友
1楼 · 发布于 2024-04-26 14:16:44

由于所需元素位于<iframe>内,因此要在元素上调用click(),您必须:

  • 诱导WebDriverWait使所需的帧可用,并切换到它
  • 诱导WebDriverWait,使所需的元素可单击
  • 您可以使用以下任一Locator Strategies

    • 使用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()
      

Here you can find a relevant discussion on Ways to deal with #document under iframe

相关问题 更多 >