【发布时间】:2014-04-21 23:32:37
【问题描述】:
嗨,我是 HtmlUnit 的新手,我有一个项目,我想从侧面获取一些信息,直到现在一切都顺利通过名称或 id 查找元素。但我无法获得以下段落元素。
<iframe id="content_ifr" frameborder="0" src="javascript:""" allowtransparency="true" title=".." style="width: 100%; height: 307px; display: block;">
<!DOCTYPE >
<html>
<head> ... </head>
<body id="tinymce" class="mceContentBody content post-type-coupon wp-editor" contenteditable="true" onload="window.parent.tinyMCE.get('content').onLoad.dispatch();" dir="ltr">
<p>------ Text from the Element i want to get ------- </p>
</body>
</html>
</iframe>
我已经试过了:
side.getByXPath("//html/body/p");// zero elements
side.getByXpath("//p");// 27 element but wrong.
side.getByXpath("//body");// 1 element but wrong.
side.getByXpath("//html");// 1 element but wrong.
side.getByXpath("//html/body/div[3]/div[3]/div[2]/div/div[4]/form/div/div/div/div[2]/div/div[2]/span/table/tbody/tr[2]/td/iframe"); // Zero elements found
我检查了代码找到的所有元素:
List<?> list =gPage.getByXPath("//p");
for(Object x:list){
HtmlElement y=(HtmlElement) x;
if(y.asXml().contains("Keyword")||y.asText().contains("Keyword")){
System.out.println(y.asText());
}
因此,总而言之,我无法通过他的文本找到段落元素。您能帮我找到 Paragraph 元素,以便我能够读取/写入它吗?
//Initialize WebClient
final WebClient webClient= new WebClient(BrowserVersion.FIREFOX_24);
webClient.getCookieManager().setCookiesEnabled(true);
webClient.getOptions().setThrowExceptionOnScriptError(false);
webClient.getOptions().setCssEnabled(false);
webClient.getOptions().setUseInsecureSSL(true);
webClient.getOptions().setThrowExceptionOnFailingStatusCode(false);
webClient.waitForBackgroundJavaScript(10000);
//Perform a login.
final HtmlPage page = webClient.getPage("");
final HtmlForm form = page.getForms().get(1);
final HtmlTextInput username = form.getInputByName("log");
final HtmlPasswordInput pw = form.getInputByName("pwd");
username.setValueAttribute("");
pw.setValueAttribute("");
@SuppressWarnings("unused")
HtmlPage page2 = (HtmlPage) form.getButtonByName("login").click();
//Get gutscheinPage
HtmlPage gutscheinPage= webClient.getPage("");
//Change Content of Textfield
HtmlPage pageFrame = (HtmlPage) gutscheinPage.getFrames().get(0).getEnclosedPage();
HtmlElement body =pageFrame.getBody();
HtmlParagraph p =(HtmlParagraph) body.getByXPath("//p").get(0);
p.setTextContent(text);
完成:更改 webClient 默认浏览器并等待 Jscript,使用 getFrames,找到正文并使用现在简单的 XPath 为我提供段落元素。
我真的希望有人会发现这对他们自己的工作有帮助。
感谢您的每一个回答。
【问题讨论】: