【问题标题】:HTMLUnit Wait For JS IssueHTMLUnit 等待 JS 问题
【发布时间】:2014-10-27 22:53:09
【问题描述】:

我正在使用 HTMLUnit 将文本放入输入框中,然后单击实际上是 JS 调用的链接。 当我使用 inputBox.setValueAttribute("example input"); 将文本放入 input 时,问题就出现了。在这种情况下,单击按钮后页面根本不会改变。 另一方面,一旦我删除inputBox.setValueAttribute("example input"); 然后单击按钮,页面内容确实会发生变化,并且包含空输入错误。

下面是我用来将文本放入相关输入然后单击按钮的代码。

public void addressToBlockPlot(){
        WebClient client = new WebClient(BrowserVersion.FIREFOX_24);
        client.getOptions().setThrowExceptionOnScriptError(false);
        client.getOptions().setThrowExceptionOnScriptError(false);
        client.setJavaScriptTimeout(10000);
        client.getOptions().setJavaScriptEnabled(true);
        client.setAjaxController(new NicelyResynchronizingAjaxController());
        client.getOptions().setTimeout(10000);


        try {
            HtmlPage page = client.getPage("http://mapi.gov.il/Pages/LotAddressLocator.aspx");

            HtmlInput inputBox = (HtmlInput)page.getHtmlElementById("AddressInput");
            final HtmlAnchor a = (HtmlAnchor) page.getElementById("helkaSubmit");

            inputBox.setValueAttribute("example input");

            a.click();
            client.waitForBackgroundJavaScript(2000); 
            HtmlPage page2= (HtmlPage) client.getCurrentWindow().getEnclosedPage(); 

            System.out.println(page2.asXml());

        } catch (Exception e) {

        }

    }

有解决这个问题的想法吗?

编辑: 我尝试过使用 inputBox.setValueAttribute(""); ,这导致收到与根本没有设置输入文本时相同的错误。

【问题讨论】:

    标签: java javascript htmlunit


    【解决方案1】:

    我有几乎类似的问题,其中 JS 需要一些时间来加载,我通过设置等待并通过添加条件重试直到页面加载成功解决了这个问题,

        int input_length = page.getByXPath("//input").size();
        int tries = 5;
        while (tries > 0 && input_length < 12) {
            tries--;
            synchronized (page) {
                page.wait(2000);
            }
            input_length = page.getByXPath("//input").size();
            System.out.println("page loaded successfully");
        }
    

    这里的 input_length 确定是否加载了所需的页面。你可以根据你的页面结构使用类似的条件。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-01-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多