【问题标题】:Click a Html Button using HtmlUnit in Java在 Java 中使用 HtmlUnit 单击 Html 按钮
【发布时间】:2018-12-21 10:46:11
【问题描述】:

我目前正在开发一个系统。我需要使用 Java 单击网站按钮。所以我正在使用 HtmlUnit 库。有一个名为https://tempmail.ninja/ 的网站会生成临时电子邮件。我需要的是单击 tempmail.ninja 中的“生成”按钮的程序,它会生成一封临时电子邮件。但问题是它没有点击。不生成电子邮件。

这是我尝试过的代码,

    try
    {
       WebClient webClient = new WebClient(BrowserVersion.CHROME);
       webClient.getOptions().setCssEnabled(true);
       webClient.getOptions().setJavaScriptEnabled(true);
       webClient.getOptions().setThrowExceptionOnFailingStatusCode(false);
       webClient.getOptions().setThrowExceptionOnScriptError(false);
       webClient.getOptions().setUseInsecureSSL(true);
       webClient.getCookieManager().setCookiesEnabled(true);
       HtmlPage page = webClient.getPage("https://tempmail.ninja");

       //Here is button id. Instead of this I used HtmlAnchor, HtmlSubmitInput and etc.
       //But any of those didn't work         
       HtmlButton htmlButton = page.getHtmlElementById("generaEmailTemporal");
       htmlButton.click();

       webClient.waitForBackgroundJavaScript(5000 * 2);   

       //Print the generated email but Currently nothing display
       HtmlTextInput htmlTextInput = (HtmlTextInput) page.getElementById("emailtemporal");
       System.out.println(htmlTextInput.getText());

       webClient.close();

    } catch(ElementNotFoundException | FailingHttpStatusCodeException | IOException ex) {
       Logger.getLogger(WebTesting.class.getName()).log(Level.SEVERE, null, ex);
    }

这里是按钮的 HTML 代码。我使用检查元素得到这个。

<p class="text-center" id="btnGeneraEmailTemporal">
<button class="btn btn-labeled btn-primary" id="generaEmailTemporal" type="button">
<span class="btn-label"><i class="fa fa-hand-o-right" aria-hidden="true"></i></span> Generate Temp Mail
</button>
</p>

我是 HtmlUnit 的新手。那么有人可以帮助我吗?我非常感谢。 谢谢你的帮助。

【问题讨论】:

    标签: java htmlunit


    【解决方案1】:

    .click() 返回更改后的页面。所以你应该是这样的:

       HtmlButton htmlButton =  page.getHtmlElementById("generaEmailTemporal");
       HtmlPage pageAfterClick = (HtmlPage)htmlButton.click();
       webClient.waitForBackgroundJavaScript(5000 * 2);      
       System.out.println(pageAfterClick.asXml()); // often displaying the page-source is more useful during development than .asText()
    

    由于 waitForBackgroundJavaScript(..) 是实验性的,并不总是有效,我更喜欢轮询,直到出现预期的文本。

    private static final int AJAX_MAX_TRIES_SECONDS = 30;
    private static final int ONE_SEC_IN_MILLISEC = 1000;
    
    /** 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)  {
        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('.');
            final long startTime = System.currentTimeMillis();
            while (System.currentTimeMillis() - startTime < ONE_SEC_IN_MILLISEC) {
                try {
                    o.wait(ONE_SEC_IN_MILLISEC);
                }
                catch (final InterruptedException e) {
                    // ignore
                }
            }
    
        }
        LOGGER.debug("_de5091bc9e_ "
                + waitingdots.append(" ajax timeout ['").append(text).append("' appeared NOT]").toString());
        LOGGER.debug("_f1030addf1_ page source:\n" + page.asXml());
        throw new RuntimeException("_ec3df4f228_");
    }
    

    【讨论】:

    • 先生,仍然没有任何反应。
    • 完全没有错误信息?显示的pageAfterClick.asXml()page.asXml()一样吗?
    • 您可以尝试其他浏览器(有时会有所帮助)(不知道为什么)。 'waitForBackgroundJavaScript(long timeoutMillis)' 是实验性的,也许你应该以不同的方式等待。
    • 该网站还实现了某种添加阻止程序检测。所以也许这也与你的尝试相冲突。
    • 感谢您的回答。但这没有帮助。现在我使用 Selenium 解决了这个问题。
    【解决方案2】:

    我已经通过使用 Selenium Web Driver 解决了这个问题。使用 selenium 单击按钮并生成电子邮件并将其传递给 HtmlUnit。

    【讨论】:

      猜你喜欢
      • 2014-06-24
      • 2013-05-12
      • 1970-01-01
      • 1970-01-01
      • 2013-04-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-04
      相关资源
      最近更新 更多