有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

web试图使用Java和HTML单元登录到站点

下面我附上了完整的代码,这是它崩溃HtmlSubmitInput button=(HtmlSubmitInput)表单的部分。getInputByName(“登录”)

我似乎遇到的问题是让程序点击按钮。我右键单击按钮并使用chrome中的inspect元素查找按钮的名称,然后使用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 ();
     }
    }

**

共 (1) 个答案

  1. # 1 楼答案

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

    它使用以下代码:

    DomElement button = (DomElement) form.getFirstByXPath("//button[@id='logincontrol_submitbutton']");
    
    text.setValueAttribute("Ziplok Java");
    
    HtmlPage resultPage = (HtmlPage) button.click();
    System.out.println(resultPage.asText());
    

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