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();
        }
    }
    
    
    
}

三、目前的問題

目標界面的內容是AJAX動態加載的,使用jsoup不能獲取到目標信息。

什么是AJAX

AJAX(Asynchronouse JavaScript And XML)異步JavaScript和XML。過在后台與服務器進行少量數據交換,Ajax 可以使網頁實現異步更新。這意味着可以在不重新加載整個網頁的情況下,對網頁的某部分進行更新。傳統的網頁(不使用Ajax)如果需要更新內容,必須重載整個網頁頁面。因為傳統的在傳輸數據格式方面,使用的是XML語法。因此叫做AJAX,其實現在數據交互基本上都是使用JSON。使用AJAX加載的數據,即使使用了JS,將數據渲染到了瀏覽器中,在右鍵->查看網頁源代碼還是不能看到通過ajax加載的數據,只能看到使用這個url加載的html代碼。

解決方案:

①直接分析AJAX調用的接口。然后通過代碼請求這個接口。

②使用selenium 模擬點擊解決該問題。

實現過程參照下兩篇文章:

java爬蟲(五)利用selenium 模擬點擊獲取動態頁面的內容

java爬蟲(六)分析AJAX接口獲取網頁動態內容

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM