2014-09-03 244 views
2

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

以下是我用于将文本放入相关输入中的代码,然后单击该按钮。

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("");尝试,这导致在接收时没有输入文本设置为全部,我得到了同样的错误。

回答

0

我几乎类似的问题,在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确定是否需要页面是否被加载。你可以根据你的页面结构使用类似的条件。