Java网络爬虫基础


做Java爬虫相比于python较为复杂一点,python的几行代码就可以抓取一个网页,Java可能需要几十行甚至跟多,因此从代码量来看python更具有爬虫优势,但是Java也不是不可以做爬虫,由于我们学习Java基础语法,为了巩固自己的基础知识,我们可以通过爬虫来掌握相关知识。

Java的java.net包中还提供了高层次网络编程类——URL,通过URL类访问互联网资源。

一、使用URL类

Java 的java.net.URL类用于请求互联网上的资源,采用HTTP/HTTPS协议,请求方法是GET方法,一般 是请求静态的、少量的服务器端数据。
URL类常用构造方法:

  • URL(String spec):根据字符串表示形式创建URL对象。
  • URL(String protocol, String host, String file):根据指定的协议名、主机名和文件名称创建URL对 象。
  • URL(String protocol, String host, int port, String file):根据指定的协议名、主机名、端口号和文件 名称创建URL对象。

URL类常用方法:

  • InputStream openStream():打开到此URL的连接,并返回一个输入流。
  • URLConnection openConnection():打开到此URL的新连接,返回一个URLConnection对象。

下面介绍一下如何使用java.net.URL类来做简单的网页抓取,示例代码如下:

mport java.io.*;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * @author : 蔡政洁
 * @email :[email protected]
 * @date : 2020/2/21
 * @time : 11:04 下午
 */
//Java网络爬虫
public class HelloWorld {
    public static void main(String[] args) {
//        Web网址
        String url = "https://www.sina.com.cn/";
        URL reqURL = null;
        try {
            reqURL = new URL(url);

        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        try (
//                打开网络通信输入流
                InputStream inputStream = reqURL.openStream();
                InputStreamReader inputStreamReader = new InputStreamReader(inputStream,"utf-8");
                BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
                ){
            StringBuilder sb = new StringBuilder();
            String line = bufferedReader.readLine();
            while (line !=null){
                sb.append(line);
                sb.append('\n');
                line = bufferedReader.readLine();
            }
//            日志输出
            System.out.println(sb);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

二、使用HttpURLConnection发送GET请求

由于URL类只能发送HTTP/HTTPS的GET方法请求,如果要想发送其他的情况或者对网络请求有更深入的控制时,可以使用HttpURLConnection类型。
代码如下:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * @author : 蔡政洁
 * @email :[email protected]
 * @date : 2020/2/21
 * @time : 11:29 下午
 */

public class HelloWorld {
    static String urlString = "https://blog.csdn.net/weixin_45366499";

    public static void main(String[] args) {
        BufferedReader br = null;
        HttpURLConnection conn = null;
        try {
            URL reqURL = new URL(urlString);
//            用reqURL.openConnection()打开一个连接,返回HttpURLConnection对象
            conn = (HttpURLConnection) reqURL.openConnection();
//            请求方法设置为get方法
            conn.setRequestMethod("GET");

//            打开网络通信输入流
            InputStream is = conn.getInputStream();
//            通过is创建InputStreamReader对象
            InputStreamReader isr = new InputStreamReader(is,"utf-8");
//            通过isr创建
            br = new BufferedReader(isr);

            StringBuilder sb = new StringBuilder();
            String line = br.readLine();
            while (line !=null){
                sb.append(line);
                sb.append('\n');
                line = br.readLine();
            }
//            输出日志
            System.out.println(sb);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        finally {
            if (conn != null){
//                断开连接
                conn.disconnect();
            }
            if (br != null){
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

三、使用HttpURLConnection发送POST请求

HttpURLConnection也可以发送HTTP/HTTPS的POST请求,下面介绍如何使用HttpURLConnection发送POST请求。

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * @author : 蔡政洁
 * @email :[email protected]
 * @date : 2020/2/22
 * @time : 6:45 下午
 */
public class HelloWorld {
//    web服务网址
    static String urlstring = "https://blog.csdn.net/weixin_45366499";
    public static void main(String[] args) {
        BufferedReader br = null;
        HttpURLConnection conn = null;
        try {
            URL reqURL = new URL(urlstring);
            //            用reqURL.openConnection()打开一个连接,返回HttpURLConnection对象
            conn = (HttpURLConnection) reqURL.openConnection();
//            HTTP请求方法为POST
            conn.setRequestMethod("POST");
//            设置请求过程中可以传递参数给服务器
            conn.setDoInput(true);

            String parm = " ";
//            设置参数
            DataOutputStream dataOutputStream = new DataOutputStream(conn.getOutputStream());
            dataOutputStream.writeBytes(parm);
            dataOutputStream.close();

//            打开网络通信输入流
            InputStream is = conn.getInputStream();
//            通过is创建 InputStreamReader对象
            InputStreamReader isr = new InputStreamReader(is,"utf-8");
//            通过isr创建BufferedReader对象
            br = new BufferedReader(isr);

            StringBuilder sb = new StringBuilder();
            String line = br.readLine();

            while (line != null){
                sb.append(line);
                sb.append('\n');
                line = br.readLine();
            }
//            日志输出
            System.out.println(sb);

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (conn != null){
                conn.disconnect();
            }
            if (br != null){
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}

四、下载案例

为了进一步熟悉URL类,介绍一个下载案例程序Downloader。通过下载网上图片

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * @author : 蔡政洁
 * @email :[email protected]
 * @date : 2020/2/22
 * @time : 7:55 下午
 */

public class Downloader {
//    web服务网址
    static String urlString = "http://a3.att.hudong.com/68/61/300000839764127060614318218_950.jpg";

    public static void main(String[] args) {
        dowmload();
    }
    private static void dowmload(){
        HttpURLConnection conn = null;
        try {
//            创建URL对象
            URL requrl = new URL(urlString);
//            打开链接
            conn= (HttpURLConnection) requrl.openConnection();
            try (
//                    从连接对象获得输入流
                    InputStream is = conn.getInputStream();
                    BufferedInputStream bufferedInputStream = new BufferedInputStream(is);
//                    创建文件输出流
                    OutputStream os = new FileOutputStream("./download.jpg");
                    BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(os);
                    ){
                byte[] buffer = new byte[1024];
                int bytesRead =bufferedInputStream.read(buffer);

                while (bytesRead !=-1){
                    bufferedOutputStream.write(buffer,0,bytesRead);
                    bytesRead = bufferedInputStream.read(buffer);
                }

            }catch (IOException e){
                e.printStackTrace();
            }
            System.out.println("下载完成!");
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (conn != null){
                conn.disconnect();
            }
        }
    }
}

运行结果就是把网上的一张图片下载到自己的电脑上,有兴趣可以试一下。

以上内容仅供参考学习,如有侵权请联系我删除!
如果这篇文章对您有帮助,左下角的大拇指就是对博主最大的鼓励。
您的鼓励就是博主最大的动力!

发布了69 篇原创文章 · 获赞 7 · 访问量 3314

猜你喜欢

转载自blog.csdn.net/weixin_45366499/article/details/104449697