首页 > 解决方案 > 如何通过 Selenium 在 iframe 中检索 html

问题描述

我想获取 iframe 标记下的所有 html 内容(例如所有 xxxx),如果 html 是这样的:

<body>
<div></div>
 ....
<div class = A>
  <div class=B>
    <div class = C> 
      <iframe class = D>
         xxxxxxx
      </iframe>
    </div>
  </div>
</div>

html = driver.switch_to.frame(driver.find_element_by_xpath("//iframe[@class='D']")) 

我试过这样的代码,这段代码有什么问题吗?错误消息是:

错误信息:

Unable to find element with xpath

标签: seleniumselenium-webdriveriframewebdriverwait

解决方案


根据您提供的HTML,您正试图<iframe>从逻辑上获取标签下的所有 html 内容,其中应该有一些<iframe>您希望与之交互的元素。因此,首先您必须诱导WebDriverWait以使框架可用并切换到它,然后再次WebDriverWait以使所需元素可见(可交互),然后您可以按如下方式提取整个源:

#WebDriverWait for the desired frame to be available and switch to it
WebDriverWait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it((By.XPATH,"//iframe[@class='D']")))
#WebDriverWait for the desired element to be visible
WebDriverWait(driver, 10).until(EC.visibilityOfElementLocated((By.XPATH, "xpath_of_desired_element")))
print(driver.page_source)

注意:您必须添加以下导入:

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

推荐阅读