【问题标题】:Htmlunit : How to get page updated after ajax dom manipulationHtmlunit:如何在 ajax dom 操作后更新页面
【发布时间】:2014-12-23 20:04:30
【问题描述】:

使用 HtmlUnit 2.15,我们正在尝试抓取第三方网站。其中有一个文本框,onblur 调用了一个 javascript 函数,该函数在同一页面上的选择框中添加了一个选项。

使用 Htmlunit,我能够成功触发 onblur 事件,但是如何处理具有新添加的选项元素的“已更改”页面?

代码sn-p:

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个选项

【问题讨论】:

  • 忘记添加 myTextBox.fireEvent(Event.TYPE_BLUR).getNewPage() 返回旧页面(有 4 个选项)

标签: javascript htmlunit


【解决方案1】:

您需要等到 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);

【讨论】:

    猜你喜欢
    • 2012-04-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-12
    • 2019-02-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多