java爬虫利用Jsoup获取需要登陆的网站中的内容(无验证码的登录)

Posted StarZhai

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java爬虫利用Jsoup获取需要登陆的网站中的内容(无验证码的登录)相关的知识,希望对你有一定的参考价值。

一、实现原理

登录之后进行数据分析,精确抓取数据。
根据上篇文章的代码,我们不仅获取了cookies,还获取了登录之后返回的网页源码,此时有如下几种种情况:
(1)若我们所需的数据就在登录之后返回的源码里面,那么我们就可以直接通过Jsoup去解析源码了,然后利用Jsoup的选择器功能去筛选出我们需要的信息;
(2)若需要的数据是需要通过请求源码里的链接得到,那么我们就先解析源码,找出这个url,然后带上cookies模拟请求这个url就可以了。
(3)若我们所需的数据完全不在源码里面,那么我们就可以不用管这个源码了。我们看浏览器,打开谷歌的network,查找分析所有url的请求和响应结果,一般情况下,总能找到那一个url(一般这个url是一个固定的url,可能参数会不一样),其返回的数据是我们期望的,然后我们模拟请求这个url,带上cookies就可以请求了。

一开始写模拟登录得时候,总觉得数据一定要在网页源码里面才能获取,所以当一个网页是由一堆js组成得就傻眼了。然后就希望能够获取渲染后的网页源码,可以尝试selenium ,以后学习使用。

 

二、详细实现过程

package debug;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.jsoup.Connection;
import org.jsoup.Connection.Method;
import org.jsoup.Connection.Response;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;

import java.io.IOException;
import org.jsoup.select.Elements;

public class test {
    public static String LOGIN_URL = "http://authserver.tjut.edu.cn/authserver/login";
    public static String USER_AGENT = "User-Agent";
    public static String USER_AGENT_VALUE = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:52.0) Gecko/20100101 Firefox/52.0";

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

         // 模拟登陆github的用户名和密码
//        String url = "http://ehall.tjut.edu.cn/publicapp/sys/zxzxapp/index.do#/consultingList";
        String url ="http://ehall.tjut.edu.cn/publicapp/sys/zxzxapp/index.do";
        get_html_num(url);        
    }

    /**
     * @param userName 用户名
     * @param pwd      密码
     * @throws Exception
     */
    public static Map<String, String> simulateLogin(String userName, String pwd) throws Exception {

        /*
         * 第一次请求 grab login form page first 获取登陆提交的表单信息,及修改其提交data数据(login,password)
         */
        // get the response, which we will post to the action URL(rs.cookies())
        Connection con = Jsoup.connect(LOGIN_URL); // 获取connection
        con.header(USER_AGENT, USER_AGENT_VALUE); // 配置模拟浏览器
        Response rs = con.execute(); // 获取响应
        Document d1 = Jsoup.parse(rs.body()); // 通过Jsoup将返回信息转换为Dom树
        List<Element> eleList = d1.select("#casLoginForm"); // 获取提交form表单,可以通过查看页面源码代码得知

        // 获取cooking和表单属性
        // lets make data map containing all the parameters and its values found in the
        // form
        Map<String, String> datas = new HashMap<>();
        for (Element e : eleList.get(0).getAllElements()) {
            // 注意问题2:设置用户名 注意equals(这个username和password也是要去自己的登录界面input里找name值)
            if (e.attr("name").equals("username")) {
                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(
                "http://authserver.tjut.edu.cn/authserver/login");
        con2.header(USER_AGENT, USER_AGENT_VALUE);
        // 设置cookie和post上面的map数据
        Response login = con2.ignoreContentType(true).followRedirects(true).method(Method.POST).data(datas)
                .cookies(rs.cookies()).execute();
            //报错Exception in thread "main" org.jsoup.HttpStatusException: HTTP error fetching URL. Status=500, 
            //  报错原因:见上边注意问题2
            // 打印,登陆成功后的信息
            //System.out.println(login.body());

        // 登陆成功后的cookie信息,可以保存到本地,以后登陆时,只需一次登陆即可
        Map<String, String> map = login.cookies();
//        for (String s : map.keySet()) {
//            System.out.println(s + " : " + map.get(s));
//        }
        return map;
    }
    
        // 实现切割某两个字之间的字符串
    public static String findstr(String str1, String strstrat, String strend) {
        String finalstr = new String();
        int strStartIndex = str1.indexOf(strstrat);
        int strEndIndex = str1.indexOf(strend);
        finalstr = str1.substring(strStartIndex, strEndIndex).substring(strstrat.length());
        return finalstr;
    }

    // 第一个,完整爬虫爬下来内容
    public static void get_html_num(String url) throws Exception {
        
        
        try {
            Map<String, String> cookies=simulateLogin("203128301", "密码保护");
//            Document doc = Jsoup.connect(url).get();
            Document doc = Jsoup.connect(url).cookies(cookies).post();
            
            // 得到html中id为content下的所有内容
            Element ele = doc.getElementById("consultingListDetail");
            // 分离出下面的具体内容
//            Elements tag = ele.getElementsByTag("td");
//            for (Element e : tag) {
//                String title = e.getElementsByTag("td").text();
//                String Totals = findstr(title, "共", "条");
//                System.out.println(Totals);
            System.out.println(doc);
//            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    
    
}

三、目前的问题

目标界面的内容是动态加载的,使用jsoup不能获取到目标信息。

解决方案:使用selenium 模拟点击解决该问题。

实现过程参照下一篇文章:java爬虫(五)利用selenium 模拟点击获取动态页面的内容

 





以上是关于java爬虫利用Jsoup获取需要登陆的网站中的内容(无验证码的登录)的主要内容,如果未能解决你的问题,请参考以下文章

java爬虫Jsoup简单学习

java爬虫问题二: 使用jsoup爬取数据class选择器中空格多选择怎么解决

Java 基于jsoup jar包的网络爬虫之登录原理

java爬虫---爬虫+基于接口的网络爬虫

如何利用java中url实现网页内容的抓取

python3下scrapy爬虫(第五卷:利用cookie模拟登陆抓取个人中心页面)