【问题标题】:How to retrive the html within an iframe through Selenium如何通过 Selenium 在 iframe 中检索 html
【发布时间】:2018-07-19 18:16:20
【问题描述】:

我想获取 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

【问题讨论】:

  • 您需要先切换到框架,然后获取其中的所有元素

标签: selenium selenium-webdriver iframe webdriverwait


【解决方案1】:

对于这样的 HTML:

<html>
<head>
<title>
Stack over flow
</title>
</head>
<body>
<p>This ius </p>
<iframe class='D'></iframe>

<p><a href="https://www.w3schools.com" target="iframe_a">W3Schools.com</a></p>  

<html>
<head>
<title>
Stack over flow iframe
</title>
</head>

<body>  
<p>This is 1 </p>

<p>This is 2 </p>

<p>This is 3 </p>
</body>
</iframe>

</body>
</html>  

你可以试试这样的:

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC 
from selenium.webdriver.common.action_chains import ActionChains

driver   = webdriver.Chrome(executable_path = r'C:/Users/abhishep/Downloads/chromedriver_win32/chromedriver.exe')
driver.maximize_window()

wait = WebDriverWait(driver,40)

driver.get("C:\\Users\\User***\\Desktop\\Python+Selenium\\SO.html")  

wait.until(EC.frame_to_be_available_and_switch_to_it((By.CSS_SELECTOR,"iframe.D")))

print(driver.page_source)
source = driver.execute_script("return document.body.innerHTML;")
print(source)

【讨论】:

  • 这有帮助吗?
【解决方案2】:

根据您提供的 HTML,因为您试图从逻辑上获取&lt;iframe&gt; 标签下的所有 html 内容,&lt;iframe&gt; 中应该有一些您希望与之交互的元素.因此,首先您必须诱导 WebDriverWait 以使 框架可用并切换到它,然后再次 WebDriverWait 以使所需元素成为 visible(interactable) 然后你可以提取整个源代码如下:

#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

【讨论】:

    猜你喜欢
    • 2019-02-15
    • 1970-01-01
    • 2019-04-18
    • 2018-07-20
    • 2020-01-02
    • 2019-06-22
    • 2021-11-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多