我正在使用HtmlUnit从网页获取数据。该网页有多个看起来相同且具有相同src值的图像,但每个图像都有一个不同的onclick事件,根据单击的图像将其指向新页面,这是我需要保存数据的新页面从。我需要遍历图像并单击每个图像以获取onclick事件的结果。目前我的代码循环遍历图像,但每个文件包含第一个图像的onclick输出。 有人能指出我遗失的地方吗?我的代码如下: 文件名中的客户是我之前在代码中声明的变量,我为每个循环更改,以便每个文件具有不同的名称。
DomNodeList<DomElement> iterable2 = page.getElementsByTagName("img");
Iterator<DomElement> i3 = iterable2.iterator();
int i = 0;
while(i3.hasNext())
{
HtmlElement element1 = null;
DomElement anElement = i3.next();
if(anElement instanceof HtmlImage)
{
HtmlImage input = (HtmlImage) anElement;
if(input.getSrcAttribute().equalsIgnoreCase("customise.gif") )
{
element1 = input;
page2 = element1.click();
webClient.waitForBackgroundJavaScript(30000);
String result = page2.asText();
try {
BufferedWriter out = new BufferedWriter(new FileWriter("Filepath//"+customer+i+".txt"));
out.write(result);
out.close();
}
catch (IOException e)
{
System.out.println("Exception ");
}
i++;
}
}
}
答案 0 :(得分:0)
我通过在HtmlUnit网站上使用针对类似问题发布的解决方案来实现这一点,可在此处找到http://htmlunit.10904.n7.nabble.com/Problem-in-clicking-multiple-javaScript-links-on-a-page-td22682.html
在链接中的线程的最后发布中使用解决方案我的代码现在是:
page = link3.click();
// Added the following line of code
Object page1Script = page.getEnclosingWindow().getScriptObject();
HtmlPage page2 = null;
Iterable<DomElement> iterable2 = page.getElementsByTagName("img");
Iterator<DomElement> i3 = iterable2.iterator();
int i = 0;
while(i3.hasNext())
{
// Added the following two lines of code
page.getEnclosingWindow().setEnclosedPage(page);
page.getEnclosingWindow().setScriptObject(page1Script);
HtmlElement element1 = null;
page2 = null;
DomElement anElement = i3.next();
if(anElement instanceof HtmlImage)
{
HtmlImage input = (HtmlImage) anElement;
if(input.getSrcAttribute().equalsIgnoreCase("customize.gif") )
{
element1 = input;
page2 = element1.click();
webClient.waitForBackgroundJavaScript(30000);
String result = page2.asText();
try {
BufferedWriter out = new BufferedWriter(new FileWriter("Filepath\\"+customer+i+".txt"));
out.write(result);
out.close();
}
catch (IOException e)
{
System.out.println("Exception ");
}
i++;
}
}
}