selenium - 如何通过 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
解决方案
根据您提供的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
推荐阅读
- android - 如何为 Android Studio 3.6 或更高版本创建自定义项目模板?
- amazon-web-services - Amazon S3 中的 GET 请求是什么
- unity3d - 下载2个应用程序后下载手机
- react-native - 试图将“[RCTVirtualText 507]”添加到“[RCTView 509]”)?
- javascript - 使用 SVG 变换“matrix()”函数时,SVG 矩形不能正确旋转/平移组
- sql - 从参考/连接表中获取所有许多:许多关系
- php - 在 PHP 中提交表单时如何保留输入字段中的值?
- ionic-framework - 离子 - 双击 iPhone 按钮上的图标问题
- c++ - 没有重载函数“strstr”的实例与参数列表匹配
- ssas - 如何在 SSAS (MSBI) 中实现列级安全性?