HTMLUnit使用javascript代码执行表单

时间:2013-04-26 17:50:31

标签: java post htmlunit

我想做的就是使用java nad HTMLUnit框架远程询问ask.fm上的问题。我认为它不起作用因为javascript代码,但我不确定。

这就是问题表格的样子:

  <form action="/userame/questions/create" autocomplete="off" id="question_form" method="post" onsubmit="$.ajax({data:$.param($(this).serializeArray()) + '&amp;authenticity_token=' + encodeURIComponent('b9o8BHnVU6KDQ/oMsdQh+ClYPlS10134bpa7bFCkqtA='), dataType:'script', type:'post', url:'/username/questions/create'}); Forms.Profile.afterSubmit(); return false;" style="display:block"><div style="margin:0;padding:0;display:inline"><input name="authenticity_token" type="hidden" value="b9o8BHnVU6KDQ/oMsdQh+ClYPlS10134bpa7bFCkqtA=" /></div>

    <div id="profile-title">
      <div class="profile-title-text">
        <span class="text-headline" dir="ltr"><span dir="ltr">KILO K ♣</span></span>
      </div>
    </div>

    <div id="postLoaderTerritory">
      <textarea class="composeQuestion-form growable-textarea" id="profile-input" name="question[question_text]"></textarea>
      <div id="postLoader"></div>
    </div>

    <div id="post_options-border">
      <div id="post_options">



        <div id="generalLevel">
          <div class="profile-title-counter" id="question_counter_span"></div>

          <input class="submitBlue submitBlue-active" id="question_submit" name="commit" onclick="RLTME.rec('profile_q_send_click');return Forms.Profile.allowSubmit(this)" type="submit" value="Ask" />


        </div>

      </div>
    </div>


        <script type="text/javascript">
//<![CDATA[

            window.setTimeout(function(){try{$("textarea#profile-input").focus();}catch(e){}},10);

//]]>
</script>




  </form>

这就是我要做的事情:

WebClient webClient = new WebClient(BrowserVersion.FIREFOX_17);
            webClient.getCookieManager().setCookiesEnabled(true);
            webClient.setJavaScriptEnabled(true);
            webClient.setThrowExceptionOnScriptError(false);
            HtmlPage page = webClient.getPage("http://ask.fm/username");
            List<HtmlForm> forms = page.getForms();

            HtmlForm ask = forms.get(1);

            HtmlSubmitInput button = ask.getInputByName("commit");
            HtmlTextArea text = ask.getTextAreaByName("question[question_text]");
            text.setText("question");
            HtmlPage click = button.click();

            webClient.closeAllWindows();

执行程序时我也收到了很多警告:

  

PM com.gargoylesoftware.htmlunit.IncorrectnessListenerImpl notify   警告:遇到过时的内容类型:'text / javascript'。

这是帖子在chrome中提交时包含的内容:

authenticity_token:b9o8BHnVU6KDQ/oMsdQh+ClYPlS10134bpa7bFCkqtA=
question[question_text]:question
authenticity_token:b9o8BHnVU6KDQ/oMsdQh+ClYPlS10134bpa7bFCkqtA=

我如何让它奏效?有什么想法吗?

1 个答案:

答案 0 :(得分:1)

您做得对,您只是没有等待提交处理。在HtmlPage click = button.click();行后添加:

webClient.waitForBackgroundJavaScript(10 * 1000);

等待10秒钟。对于更好的解决方案,您也可以尝试this one