htmlunit:返回一个完全加载的页面

gr8qqesn  于 2021-06-30  发布在  Java
关注(0)|答案(1)|浏览(510)

我正在使用htmlunit library for java以编程方式操作网站。我找不到解决问题的有效方法:如何确定所有ajax调用都已完成并返回完全加载的网页?以下是我尝试过的:
首先我创造 WebClient 示例并调用我的方法 processWebPage(String url, WebClient webClient) ```
WebClient webClient = null;
try {
webClient = new WebClient(BrowserVersion.FIREFOX_3_6);
webClient.setThrowExceptionOnScriptError(false);
webClient.setThrowExceptionOnFailingStatusCode(false);
webClient.setJavaScriptEnabled(true);
webClient.setAjaxController(new NicelyResynchronizingAjaxController());
} catch (Exception e) {
System.out.println("Error");
}
HtmlPage currentPage = processWebPage("http://www.example.com", webClient);

下面是我的方法,它应该返回一个完全加载的网页:

private static HtmlPage processWebPage(String url, WebClient webClient) {
HtmlPage page = null;
try {
page = webClient.getPage(url);
} catch (Exception e) {
System.out.println("Get page error");
}
int z = webClient.waitForBackgroundJavaScript(1000);
int counter = 1000;
while (z > 0) {
counter += 1000;
z = webClient.waitForBackgroundJavaScript(counter);
if (z == 0) {
break;
}
synchronized (page) {
System.out.println("wait");
try {
page.wait(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
System.out.println(page.asXml());
return page;
}

那个 `z` 变量应返回 `0` 如果没有javascript可供加载。
有什么想法吗?提前谢谢。
编辑:我找到了一个部分工作的解决方案,我的问题,但在这种情况下,我应该知道如何响应页面看起来。例如,如果完全加载的页面包含文本“complete”,我的解决方案是:

HtmlPage page = null;
int PAGE_RETRY = 10;
try {
page = webClient.getPage("http://www.example.com");
} catch (Exception e) {
e.printStackTrace();
}
for (int i = 0; !page.asXml().contains("complete") && i < PAGE_RETRY; i++) {
try {
Thread.sleep(1000 * (i + 1));
page = webClient.getPage("http://www.example.com");
} catch (Exception e) {
e.printStackTrace();
}

}
但是,如果我不知道一个完全加载的页面是什么样子的,那该怎么办呢?
t3psigkw

t3psigkw1#

试试这个:

HtmlPage page = null;
try {
    page = webClient.getPage(url);
} catch (Exception e) {
    System.out.println("Get page error");
}
JavaScriptJobManager manager = page.getEnclosingWindow().getJobManager();
while (manager.getJobCount() > 0) {
    Thread.sleep(1000);
}
System.out.println(page.asXml());
return page;

相关问题