[英]Htmlunit : How to get page updated after ajax dom manipulation
使用HtmlUnit 2.15,我們正在嘗試抓取第三方網站。 其中有一個文本框,onblur調用了javascript函數,該函數將選項添加到同一頁面上的選擇框。
使用Htmlunit,我能夠成功觸發onblur事件,但是如何獲取具有新添加的option元素的“ changed”頁面的句柄?
程式碼片段:
final HtmlPage page = webClient.getPage(myUrl);
HtmlSelect selectDropDown = (HtmlSelect)page.getElementByName(selectname);
List<HtmlOption> options = clickThis.getOptions(); // returns 4 options
HtmlTextInput myTextBox = page.getElementByName(textboxname);
myTextBox.setValueAttribute("myText");
myTextBox.fireEvent(Event.TYPE_BLUR);
//現在如何獲取“已更新”頁面? 它應該有5個選擇
您需要等待javascript更改頁面。 我的經驗是,這可能需要一段時間。 尤其是在調用服務器的過程中。
到目前為止,我的嘗試是輪詢頁面,直到某些事情改變了我期望的方式。
這是一種等待給定文本顯示在頁面上的方法。
private static final int AJAX_MAX_TRIES_SECONDS = 30;
/**
* Waits until the given 'text' appeared or throws an
* WaitingForAjaxTimeoutException if the 'text' does not appear before we timeout.
* @param page
* @param text The text which indicates that ajax has finished updating the page
* @param waitingLogMessage Text for the log-output. Should indicate where in the code we are, and what are we waiting for
* @throws WaitingForAjaxTimeoutException
*/
public static void waitForAjaxCallWaitUntilTextAppears(//
@Nonnull final HtmlPage page, //
@Nonnull final String text,//
@Nonnull final String waitingLogMessage) throws WaitingForAjaxTimeoutException {
LOGGER.debug("_5fd3fc9247_ waiting for ajax call to complete ... [" + waitingLogMessage + "]");
final StringBuilder waitingdots = new StringBuilder(" ");
for (int i = 0; i < AJAX_MAX_TRIES_SECONDS; i++) {
if (page.asText().contains(text)) {
waitingdots.append(" ajax has finished ['").append(text).append("' appeared]");
LOGGER.debug("_8cd5a34faf_ " + waitingdots);
return;
}
waitingdots.append('.');
wait(page);
}
LOGGER.debug("_de5091bc9e_ "
+ waitingdots.append(" ajax timeout ['").append(text).append("' appeared NOT]").toString());
LOGGER.debug("_f1030addf1_ page source:\n" + page.asXml());
throw new WaitingForAjaxTimeoutException();
}
還要確保啟用了javascript。 (默認設置):
webClient.getOptions().setJavaScriptEnabled(true);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.