首页 > 如何使用jsoup登陆需要用户名和密码的网页

如何使用jsoup登陆需要用户名和密码的网页

/**
     * 模拟登陆Iteye
     *
     * @param userName 用户名
     * @param pwd 密码
     *
     * *
     */
    public void login(String userName, String pwd) throws Exception {

        //第一次请求
        Connection con = Jsoup.connect("https://www.pixiv.net/login.php");//获取连接
        con.header("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:29.0) Gecko/20100101 Firefox/29.0");//配置模拟浏览器
        Response rs = con.execute();//获取响应
        Document d1 = Jsoup.parse(rs.body());//转换为Dom树
        List<Element> et = d1.select("#login-form");//获取form表单,可以通过查看页面源码代码得知
        
        if(et.isEmpty()){
            System.out.println("获取form表单失败");
            return;
        }

        //获取,cooking和表单属性,下面map存放post时的数据
        Map<String, String> datas = new HashMap<>();
        for (Element e : et.get(0).getAllElements()) {
            if (e.attr("name").equals("name")) {
                e.attr("value", userName);//设置用户名
            }

            if (e.attr("name").equals("password")) {
                e.attr("value", pwd); //设置用户密码
            }

            if (e.attr("name").length() > 0) {//排除空值表单属性
                datas.put(e.attr("name"), e.attr("value"));
            }
        }

        /**
         * 第二次请求,post表单数据,以及cookie信息
         *
         * *
         */
        Connection con2 = Jsoup.connect("https://www.pixiv.net/login.php");
        con2.header("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:29.0) Gecko/20100101 Firefox/29.0");
        //设置cookie和post上面的map数据
        Response login = con2.ignoreContentType(true).method(Method.POST).data(datas).cookies(rs.cookies()).execute();
        //打印,登陆成功后的信息
        System.out.println(login.body());

        //登陆成功后的cookie信息,可以保存到本地,以后登陆时,只需一次登陆即可
        Map<String, String> map = login.cookies();
        for (String s : map.keySet()) {
            System.out.println(s + "      " + map.get(s));
        }

    }

问题出在获取不了form表单那里,et为空。


咳咳....题主提供的网站不错....

这个网站可以这样登录:


public static void main(String[] args) throws IOException {

    Map<String, String> loginPageCookies = Jsoup.connect("https://www.pixiv.net/login.php")
            .method(Connection.Method.POST).execute().cookies();

    String userName = "";
    String password = "";

    Connection.Response loginResponse = Jsoup.connect("https://www.pixiv.net/login.php")
            .data("mode", "login", "pixiv_id", userName, "pass", password, "skip", "1")
            .cookies(loginPageCookies)
            .method(Connection.Method.POST).execute();

    Map<String, String> userCookies = loginResponse.cookies();

    System.out.println(Jsoup.connect("https://www.pixiv.net")
            .cookies(userCookies).get().body());

}
【热门文章】
【热门文章】