java编写模拟登陆爬虫

来源:互联网 发布:学生怒骂日本记者知乎 编辑:程序博客网 时间:2024/06/01 07:36

—-首先为什么能用程序去登陆网站?因为当我们访问网站后,服务端会生成一个sessionId,保存在客户端的cookie中,如何这个sessionId是正确登陆是返回的id,那么当我们访问需要登录才能访问的网页时,将这个sessionId加入访问数据中,服务器就知道我们已经登录了,所以就可以爬取需要登录的页面的内容

我们需要用到的工具:
Jsoup:http://download.csdn.net/download/w3045872817/9972534

代码为:

package com.imooc.spider;import java.io.BufferedWriter;import java.io.FileOutputStream;import java.io.IOException;import java.io.OutputStreamWriter;import java.util.Map.Entry;import java.util.Set;import org.jsoup.Connection;import org.jsoup.Jsoup;import org.jsoup.nodes.Document;import org.jsoup.nodes.Element;public class SplitTable {    public static void main(String[] args) throws IOException {        //想要爬取的url        String url = "http://jwcnew.nefu.edu.cn/dblydx_jsxsd/xskb/xskb_list.do?Ves632DSdyV=NEW_XSD_PYGL";        String username = "";        String password = "";        String sessionId = getSessionInfo(username,password);        spiderWebSite(sessionId,url);    }    //获取sessionId    private static String getSessionInfo(String username,String password) throws IOException{        //登录网站,返回sessionId信息        Connection.Response res = Jsoup.connect("http://jwcnew.nefu.edu.cn/dblydx_jsxsd/xk/LoginToXk")//要登录的url可以在登录页面将post改为get查看它是如何传参数的(我这里选择的是东北林业大学:具体可以查看下图)                .data("USERNAME", username, "PASSWORD", password)                .method(Connection.Method.POST)                .timeout(10000)                .execute();        //获得sessionId        String sessionId = res.cookie("JSESSIONID");        System.out.println(sessionId);        return sessionId;    }    //爬取目标网站    private static void spiderWebSite(String sessionId,String url) throws IOException{        //爬取        Document doc = Jsoup.connect(url).cookie("JSESSIONID", sessionId).timeout(10000).get();        Element table = doc.getElementById("kbtable");        //System.out.println(table);        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("F:/table.html")));        bw.write(new String(table.toString().getBytes()));        bw.flush();        bw.close();    }}

修改post为get图:打开登录界面按F12,选择Elements,点击箭头
这里写图片描述

这里写图片描述

得到字段为USERNAME=1232&PASSWORD=12312

你们自己试一试自己的吧,这个只适合没有验证码的

原创粉丝点击