尝试使用 Java 和 HTML 单位登录站点

Trying to login to a site using Java and HTML Unit

下面我附上了完整的代码,这是它崩溃的部分 HtmlSubmitInput button = (HtmlSubmitInput) form.getInputByName("login");

我似乎遇到的问题是让程序点击按钮。我右键单击按钮并使用 chrome 中的检查元素找到按钮的名称,然后使用 getInputByName 但我似乎遗漏了一些东西。

**

    import com.gargoylesoftware.htmlunit.WebClient;
    import com.gargoylesoftware.htmlunit.html.HtmlForm;
    import com.gargoylesoftware.htmlunit.html.HtmlPage;
    import com.gargoylesoftware.htmlunit.html.HtmlSubmitInput;
    import com.gargoylesoftware.htmlunit.html.HtmlTextInput;

    public class GoogleRobotSearch {
     private String bUrl;

     public GoogleRobotSearch (String url) throws Exception {
      bUrl = url;
     }

     public void search () throws Exception {
      WebClient wb = new WebClient ();
      HtmlPage p = (HtmlPage) wb.getPage(bUrl);

      HtmlForm form = p.getFormByName("frmLogin");
      HtmlTextInput text = (HtmlTextInput) form.getInputByName("username");    

      HtmlSubmitInput button = (HtmlSubmitInput) form.getInputByName("login");

      text.setValueAttribute("Ziplok Java");

      HtmlPage resultPage = (HtmlPage) button.click();
      System.out.println(resultPage.asText());



     }

     public static void main (String args[]) throws Exception {
      GoogleRobotSearch xyro = new GoogleRobotSearch ("http://www.pof.com/");
      xyro.search ();
     }
    }

**

请注意登录按钮不是输入。

它适用于以下代码:

DomElement button = (DomElement) form.getFirstByXPath("//button[@id='logincontrol_submitbutton']");

text.setValueAttribute("Ziplok Java");

HtmlPage resultPage = (HtmlPage) button.click();
System.out.println(resultPage.asText());

我没有使用输入,而是使用通用 DomElement 并通过其 ID 获取项目。您还可以使用特定于按钮的对象,但 DomElement 工作正常:)