我正在努力获取 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"));
关于java - 如何在java中让body保存iframe的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13646163/