可以直接添加进项目中使用,仅需改为自己想要的数据格式;

接口数据读取;

添加正则表达式或固定格式可爬取特定数据:(如邮件,电话号码,QQ号码等)

可用于在其他网站爬取数据,开发其第三方网站;

exe小程序数据保存在本地;

源码接口爬来的Json数据,需自己解析,灵活处理

java 爬取json数据 java爬取接口数据_java 爬取json数据

package com.haoxuan.view;

import java.awt.BorderLayout;

public class CreeperOption {

    private static JFrame frame;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    CreeperOption window = new CreeperOption();
                    window.frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the application.
     */
    public CreeperOption() {
        initialize();
    }

    /**
     * Initialize the contents of the frame.
     */
    private void initialize() {
        frame = new JFrame();
        frame.setBounds(100, 100, 450, 300);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocation(800, 350);

        frame.setSize(400, 400);
        //设置窗体标题
        frame.setTitle("爬虫入口");
        //设置窗口最小化时显示的图标,可选。
                Image img = new ImageIcon(this.getClass().
                             getResource("/images/001.jpg")).getImage(); 
                frame.setIconImage(img);
                MainLoginPanel loginPanel = new MainLoginPanel();
                frame.setContentPane(loginPanel);

                //设置窗口其他显示属性
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setVisible(true);
                frame.setResizable(false);
                //注册窗口监听器
                frame.addWindowListener(new WindowsHandler());  
            }
            //登录容器panel构造,将所有控件元素装入容器
            private class MainLoginPanel extends JPanel{
                JLabel picLabel;
                JButton stuLoginButton,tchLoginButton;
                JPanel infoPanel;
                public MainLoginPanel(){
                //生成所有控件的对象
                picLabel =new JLabel();
                stuLoginButton = new JButton("点击跳转到信息配置界面");//构造器参数为按钮显示文本
                infoPanel=new JPanel();
                //设置MainLoginPanel布局为BorderLayout
                setLayout(new BorderLayout());

                //依次添加pic、login信息控件到面板容器, 
                //并设置infoPanel布局管理器为FlowLayout。 
                infoPanel.setLayout(new FlowLayout(FlowLayout.CENTER));

                picLabel.setSize(400, 300); 
                ImageIcon image = new ImageIcon(frame.getClass().
                                  getResource("/images/top2.jpg")); 
                image.setImage(image.getImage().getScaledInstance( picLabel.
                    getWidth(),picLabel.getHeight(), Image.SCALE_DEFAULT)); 
                 picLabel.setIcon(image);
                 infoPanel.add(picLabel);
                 infoPanel.add(stuLoginButton);
                 //让infoPanel充满整个容器
                 add(infoPanel,BorderLayout.CENTER);  
                 //生成事件监听对象
                ButtonAction buttonAction = new ButtonAction();
                //事件注册事件监听器
                stuLoginButton.addActionListener(buttonAction);
            }
            private class ButtonAction implements ActionListener{

                public void actionPerformed(ActionEvent e) {
                    // TODO Auto-generated method stub
                    if(e.getSource().equals(stuLoginButton)){
                        //所有swing组件必须由事件分派线程(event dispatch thread)
                        //进行配置,线程将鼠标点击和按键控制转移到用户接口组件。
                            EventQueue.invokeLater(new Runnable() { 
                                public void run() {  
                                    CreeperFrame cframe = new CreeperFrame();
                                    }});    
                    }
                              frame.setVisible(false); 

              }
            }

    }
}

这里是主界面,想用Java swing 写界面的,可以先在eclipse中装一个Windowsbuild插件,边拖边看边写,有一点前端基础的同学上手都很快,但是基本gui已经过时了 ,但是写写小的引用程序还是可以。

java 爬取json数据 java爬取接口数据_exe_02

package com.haoxuan.view;

    import java.awt.Color;

    public class CreeperFrame extends JFrame {

        private JPanel contentPane;
        private JTextField srcAdress;
        private JTextField destAdress;
        private JTextField name;
        private JTextField type;
        private JTextField option;
        /**
         * Create the frame.
         */
        public CreeperFrame() {

            //主界面框设置
            setForeground(Color.BLACK);
            setBackground(Color.WHITE);
            setIconImage(Toolkit.getDefaultToolkit().getImage(CreeperFrame.class.getResource("/images/001.jpg")));
            setTitle("个人填写爬取所需信息");
            setResizable(false);
            setVisible(true);
            setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
            setBounds(100, 100, 450, 450);
            setLocation(800, 350);
            contentPane = new JPanel();
            contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
            setContentPane(contentPane);
            contentPane.setLayout(null);

            //中间标题
            JLabel lblNewLabel = new JLabel("欢迎使用皓轩网页数据爬取");
            lblNewLabel.setForeground(Color.YELLOW);
            lblNewLabel.setBounds(126, 14, 228, 33);
            contentPane.add(lblNewLabel);
            lblNewLabel.setFont(new Font("微软雅黑", Font.BOLD, 18));

            //创建一个panel
            JPanel panel = new JPanel();
            panel.setBorder(new LineBorder(Color.GRAY));
            panel.setBounds(14, 60, 413, 251);
            contentPane.add(panel);
            panel.setLayout(null);

            JLabel label = new JLabel("爬取地址");
            label.setFont(new Font("微软雅黑", Font.BOLD, 18));
            label.setBounds(14, 12, 95, 34);
            panel.add(label);

            JLabel label_1 = new JLabel("存放地址");
            label_1.setFont(new Font("微软雅黑", Font.BOLD, 18));
            label_1.setBounds(14, 64, 75, 33);
            panel.add(label_1);

            JLabel label_2 = new JLabel("文件名称");
            label_2.setFont(new Font("微软雅黑", Font.BOLD, 18));
            label_2.setBounds(14, 110, 75, 37);
            panel.add(label_2);

            JLabel label_4 = new JLabel("文件格式");
            label_4.setFont(new Font("微软雅黑", Font.BOLD, 18));
            label_4.setBounds(14, 160, 75, 28);
            panel.add(label_4);

            JLabel label_3 = new JLabel("是否连续");
            label_3.setFont(new Font("微软雅黑", Font.BOLD, 18));
            label_3.setBounds(14, 201, 75, 28);
            panel.add(label_3);


            srcAdress = new JTextField();
            srcAdress.setText("例如:http://www.myhaoxuan.cn:8080/cdffcai");
            srcAdress.setBounds(103, 12, 296, 31);
            panel.add(srcAdress);
            srcAdress.setColumns(10);

            destAdress = new JTextField();
            destAdress.setText("例如:E:");
            destAdress.setBounds(103, 59, 296, 35);
            panel.add(destAdress);
            destAdress.setColumns(10);

            name = new JTextField();
            name.setText("例如:test");
            name.setBounds(103, 110, 296, 34);
            panel.add(name);
            name.setColumns(10);

            type = new JTextField();
            type.setText("例如:txt、html、jpg、、、");
            type.setBounds(103, 164, 296, 28);
            panel.add(type);
            type.setColumns(10);

            option = new JTextField();
            option.setText("例如:true/false");
            option.setBounds(103, 198, 296, 35);
            panel.add(option);
            option.setColumns(10);

            //最后一个panel
            JPanel panel_1 = new JPanel();
            panel_1.setBounds(0, 324, 439, 66);
            contentPane.add(panel_1);
            panel_1.setLayout(null);

            //创建一个按钮
            JButton btnButton = new JButton("确认提交");
            btnButton.setForeground(Color.BLUE);
            btnButton.setBackground(Color.YELLOW);
            //给按钮绑定监听事件
            btnButton.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                            try {
                                CreeperController creeperController = new CreeperController(srcAdress.getText().trim(), destAdress.getText().trim(), name.getText().trim(), type.getText().trim(),option.getText().trim());
                                boolean flag = creeperController.crawling();
                                if(flag){
                                    JOptionPane.showMessageDialog(null, "爬取成功!请去"+destAdress.getText()+name.getText()+"."+type.getText()+"查看文件");
                                }else{
                                    JOptionPane.showMessageDialog(null, "爬取失败!");
                                }
                            } catch (Exception e1) {
                                // TODO Auto-generated catch block
                                e1.printStackTrace();
                                JOptionPane.showMessageDialog(null, "爬取失败!");
                            }
                }           
            });
            btnButton.setFont(new Font("微软雅黑", Font.BOLD, 20));
            btnButton.setBounds(155, 13, 126, 40);
            panel_1.add(btnButton);
        }
    }

在网上找出接口,然后就是想爬什么爬什么 ,很方便使用,但是关键要找出借口,比如爬取的是数据接口,就应该选择连续存储,不然会让所用数据都在一个文件里面,因为爬数据时多半都伴随着分页,需要不断修改原地址参数所以要选择连续存储。其余的如:网站,MP3,MP4,js,HTML。。。等都不需要连续存储,爬一次就是一个文件。

package com.haoxuan.view;

import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

public class WindowsHandler extends WindowAdapter {

    public void windowClosing(WindowEvent e) {
        // TODO Auto-generated method stub
        System.exit(0);
    }


    public void windowClosed(WindowEvent e) {
        // TODO Auto-generated method stub
        super.windowClosed(e);
    }

    public void windowIconified(WindowEvent e) {
        // TODO Auto-generated method stub
        super.windowIconified(e);
    }


    public void windowActivated(WindowEvent e) {
        // TODO Auto-generated method stub
        super.windowActivated(e);
    }

    public void windowDeactivated(WindowEvent e) {
        // TODO Auto-generated method stub
        super.windowDeactivated(e);
    }

}

这里是gui的窗口事件类,绑定上就可以了


这里就是爬取数据的部分了,脱机可用,可以将main的注释掉,跑起来试试效果,感觉很棒

package com.haoxuan.controller;

import java.util.Scanner;

public class CreeperController {

    private CreeperTool creeperTool;
    private String args[] = new String[5];

    /**
     * 构造函数
     * @param srcAddress  爬取地址
     * @param destAddress   目的地址
     * 
     * @param name    文件名
     * @param type    文件格式
     * @param option   是否连续
     */
    public CreeperController(String srcAddress,String destAddress,String name,String type,String option){
        super();
        args[0] = srcAddress;
        args[1] = destAddress;
        args[2] = name;
        args[3] = type;
        args[4] =option;
        this.creeperTool = new CreeperTool();
    }

    public boolean crawling(){
         try {
            this.creeperTool.creeper(args);
            return true;
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return false;
        }   
    }
    //不用界面的   到这里就可以了,去掉注释测试就可以了,没有加正则 注意书写格式!!
//  public static void main(String[] args) {
//       //系统自带计时,以毫秒为单位 ,记录当前距离1970年的毫秒数   
//      long startTime = System.currentTimeMillis();
//      Scanner in = new Scanner(System.in);
//      System.out.println("--     欢迎使用皓轩 网页&接口 爬虫小程序      --");  
//      System.out.println("");  
//      System.out.println("--请输入正确的网址如http://www.baidu.com--");
//      String srcAddress = in.next();
//      System.out.println("--请输入正确的存放地址如:E:");
//      String destAddress = in.next();
//      System.out.println("--请输入正确的文件名如:test");
//      String name = in.next();
//      System.out.println("--请输入正确的文件格式如:txt、html、js、jpg、、");
//      String type = in.next();
//      System.out.println("--请输入是否连续存如:true/false");
//      String option = in.next();
//      CreeperController cc = new CreeperController(srcAddress, destAddress, name, type, option);
//      cc.crawling();    
//      System.out.println(" —————————————————————\t");  
//      System.out.println("|数据爬取成功,请到"+args[1]+"目录下查看"+args[2]+"文档|\t");
//      System.out.println("|                                         |");  
//      System.out.println("|如需重新爬取,请再次执行程序,谢谢您的使用|\t");  
//      System.out.println(" —————————————————————\t");
//      CreeperController cc = new CreeperController("http://www.myhaoxuan.cn:8080/cdffcai","E:", "test", ".txt", "true");
//        cc.crawling();   
//  }
}

下面是核心工具,开了源码的会知道只要可以建立连接 什么数据都可以爬取,主要是针对web端的爬取,如果是想在c/s端爬取,需要修改连接,很简短,把url连接改掉,使用套接字 ip地址与端口号的方式连接

package com.haoxuan.controller;

import java.io.BufferedReader;  
import java.io.File;  
import java.io.FileWriter;  
import java.io.InputStreamReader;  
import java.io.Writer;  
import java.net.URL;  
import java.net.URLConnection;  
import java.sql.Time;  
import java.util.Scanner;  
import java.util.regex.Matcher;  
import java.util.regex.Pattern;  
public class CreeperTool {

    /**
     * 爬取数据
     * @param args --args[0]:爬取网址  args[1]:存取地址  args[2]:文件名  args[3]:文件格式  args[4]:是否单文本多读
     * @throws Exception
     */
    public void creeper(String[] args) throws Exception {// 本程序内部异常过多为了简便,不一Try,直接抛给上层CreeperController捕获
            //系统自带计时,以毫秒为单位 ,记录当前距离1970年的毫秒数    
            long startTime = System.currentTimeMillis();
            //创建文件, 并指明输出地址和输出文件名  
            File file = new File(args[1] + File.separator + args[2] +"."+ args[3]);
            Writer outWriter = null;// 实例化outWriter类
            if("true".equals(args[4])){//这样可以直接就预防空指针异常了
                //不覆盖原文件类型
                outWriter = new FileWriter(file,true);
            }else{
                //覆盖原文件类型
                outWriter = new FileWriter(file,false);
            }  
            // 实例化URL类。
            URL url = new URL(args[0]);  
            // 取得链接  
            URLConnection conn = url.openConnection();
            // 取得网页数据  
            BufferedReader buff = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line = null;  
            outWriter.write("<!-- 该网页中所包含的的数据如下所示:--> \r\n");  
            int i = 0;//记录爬取行数
            while ((line = buff.readLine()) != null) {  
                outWriter.write(line + "\r\n");// 将匹配的字符输入到目标文件    
                i++;
            }  
            long endTime = System.currentTimeMillis();  
            String UseTime=(endTime-startTime)+"";//耗时多少
            outWriter.write("<!-- --------------------------------------------------------\r\n");  
            outWriter.write("本次爬取页面地址:"+args[0]+"\r\n");  
            outWriter.write("爬取耗时:"+UseTime+"毫秒\r\n");  
            outWriter.write("本次共爬的行数:"+i+"条\r\n");  
            outWriter.write("****谢谢您的使用****\r\n");  
            outWriter.write("------------------------------------------------------ -->");  
            outWriter.close();// 关闭文件输出操作  
    }  
}