我正在尝试获取iframe标签下的数据。我想要数据在body标签下。但是我没有得到正确的输出。这是我的HTML页面如下所示:

<iframe id="sharetools-iframe" width="100%" height="100%" frameborder="0" style="z-index: 1000; position: relative; visibility: visible; " scrolling="no" allowtransparency="true" src="some url here"></iframe>
#document
<html><head><script type="text/javascript">window.WIDGET_ID = 'sharepopup';</script>
<base href="href here">
<link rel="stylesheet" href="href here">
<script src="url here"></script>

<script type="text/javascript" src="url here"></script></head>
<body>
body contents are here........
..............................
</div></div></body></html>


我使用了以下代码:

WebDriver webDriver = new FirefoxDriver();
webDriver.get("url to open");
String htmlPage = webDriver.getPageSource();
Tidy tidy = new Tidy();
InputStream inputStream = new ByteArrayInputStream(htmlPage.getBytes());
Document doc = tidy.parseDOM(inputStream, null);
Element element = doc.getElementById("sharetools-iframe");


在这里我得到的元素为null。我也将其类型转换如下:

HTMLIFrameElement iframeElement = (HTMLIFrameElement) doc.getElementById("sharetools-iframe");


但是让iframeElement为null。

我还使用了jsoup解析器,如下所示:

Document doc = Jsoup.parse(htmlPage);
org.jsoup.nodes.Element iframeElement= doc.getElementById("sharetools-iframe");


在这里,我将输出<iframe id="sharetools-iframe" width="100%" height="100%" frameborder="0" style="z-index: 1000; position: relative; visibility: visible; " scrolling="no" allowtransparency="true" src="some url here"></iframe>作为iframeElement获取,但没有获取正文内容。

请指导我如何获取iframe的主体内容。

最佳答案

您需要切换到iframe,然后才能与内容进行交互。
例如获取身体:

driver.switchTo().frame(driver.findElement(By.id("sharetools-iframe"))).findElement(By.tagName("body"));

08-06 03:25
查看更多