웹용 프로그래밍 방식으로 웹 사이트를 조작하기 위해 Java 용 HtmlUnit 라이브러리를 사용하고 있습니다. 내 문제에 대한 해결 방법을 찾을 수 없습니다 : 모든 AJAX 호출이 완료되었는지 확인하고 완전히로드 된 웹 페이지를 반환하는 방법? 여기에 내가 시도 내용은 다음과 같습니다htmlunit : 완전히로드 된 페이지를 반환하십시오.
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;
}
:
첫째로 나는 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);
그리고 여기에 완전히로드 된 웹 페이지를 반환해야 내 방법입니다 로드 할 JavaScript가 남아 있지 않은 경우 해당 변수는 0
을 반환해야합니다.
의견이 있으십니까? 미리 감사드립니다.
편집 : 문제가 부분적으로 해결되었지만이 경우 응답 페이지의 모양을 알아야합니다.
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();
}
}
하지만 내가 완전히로드 페이지처럼 보이는 방법을 모르는 경우 해결책이 될 것입니다 : 완전히로드 된 페이지는 "완전한"텍스트가 포함 된 경우 예를 들어, 내 솔루션이 될 것이다?
을하지만, 작동, 감사합니다! – justasd
도와 줘서 기쁩니다! 정답으로 표시하십시오! 감사! – brnfd
내가 게시 한 게시물이 노골적 일지라도, 귀하의 페이지에서 타이머가 실행될 때 문제가 발견됩니다. 따라서 waitforBackground 메서드를 사용하더라도 매개 변수로 주어진 시간의 끝까지 기다리고 있습니다. –