使用HtmlUnit登录百度

环境

java 1.7

HtmlUnit 2.18

eclipse 4.4.2

maven 配置:

<dependency>
            <groupId>net.sourceforge.htmlunit</groupId>
            <artifactId>htmlunit</artifactId>
            <version>2.18</version>
        </dependency>

java代码

public void loginBaidu(){
        try {
        WebClient webClient = new WebClient();
        HtmlPage htmlPage = webClient.getPage("https://www.baidu.com/");
        System.out.println(htmlPage.asXml());

        HtmlAnchor loginAnchor = (HtmlAnchor) htmlPage.getElementByName("tj_login");
        System.out.println(loginAnchor.asXml());
        
        HtmlPage loginPage = loginAnchor.click();
        System.out.println(loginPage.asXml());
        
        HtmlTextInput userNameInput = (HtmlTextInput) loginPage.getElementById("TANGRAM__PSP_8__userName");
        userNameInput.click();
        userNameInput.setValueAttribute("loginName");
        HtmlPasswordInput pwdInput = (HtmlPasswordInput) loginPage.getElementById("TANGRAM__PSP_8__password");
        pwdInput.click();
        pwdInput.setValueAttribute("password");
        
        HtmlSubmitInput submitInput = (HtmlSubmitInput) loginPage.getElementById("TANGRAM__PSP_8__submit");
        HtmlPage loginAfterPage = submitInput.click();

        System.out.println(loginAfterPage.asXml());
        
        HtmlPage suPage = loginAfterPage.getElementById("su").click();
        System.out.println(suPage.asXml());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

实现了简单的登录功能,后面的其他功能可以自己发挥一下

posted @ 2015-09-22 14:20  唐凯  阅读(1628)  评论(0编辑  收藏  举报