JAVA爬虫入门实例(详细)

前言

项目中用到了爬虫爬数据,之前没接触过,查了资料然后搭了几遍demo,在后台读取dom感觉很新鲜,之前在研究的时候发现网上的资料大多是一些项目里直接拿出来的,有的注释都没有,还有许许多多的小错误
而且很多人在用 HttpClient 创建连接(该方法已经过时许久,基本可以断定都是用老项目复制出来的),
本文以 http://www.baidu.com 为例,所以不废话直接开始

一、创建连接

创建连接有两种方式,第二种方式简介易懂,但是观其底层还是第一种方式的封装:

  1. 通过 HttpURLConnection 获取信息:如果项目里没有封装好的基类,就要自己手写请求(麻烦点,但是易懂)
		//定义请求 URL 这里用百度举例
        URL url = new URL("http://www.baidu.com");
        //实例化对象,官方文档就是用这个方式实例化 HttpURLConnection
        HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
        httpURLConnection.setConnectTimeout(1000);
        httpURLConnection.setReadTimeout(2000);
  1. 通过 Jsoup.connect(url) 获取信息:简单,可直接获取
		Jsoup.connect("http://www.baidu.com");

二、获取Document

  1. HttpURLConnection :先上一个工具类
	/**这个方法是将InputStream转化为String*/
    public static String convertStreamToString(InputStream is) throws IOException {
        if (is == null){
            return "";
        }
        BufferedReader reader = new BufferedReader(new InputStreamReader(is,"utf8"));
        StringBuilder sb = new StringBuilder();
        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        reader.close();
        return sb.toString();
    }
 		//定义请求 URL 这里用百度举例
        URL url = new URL("http://www.baidu.com");
        //实例化对象,官方文档就是用这个方式实例化 HttpURLConnection
        HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
        httpURLConnection.setConnectTimeout(1000);
        httpURLConnection.setReadTimeout(2000);
        //确认成功与否
        if (httpURLConnection.getResponseCode() == 200){
            //获取输入流
            InputStream inputStream = httpURLConnection.getInputStream();
            //获取 html 页面
            String html = convertStreamToString(inputStream);
            //拿到 Document
            Document document = Jsoup.parse(html);
        }

大家可以把 String html = convertStreamToString(inputStream); 打印一下,发现就是一个网页的代码
在这里插入图片描述

  1. Jsoup.connect(url) :这就简单多了,直接调用.get方法就可以获取Document
		Document document = Jsoup.connect("http://www.baidu.com").get();

三、获取数据

前面我们已经获取到最重要的页面 Document 接下来就可以通过选择器获取我们想要的数据
在这里插入图片描述

		//这里是获取 Document 为表方便使用第二种方式 
		Document document = Jsoup.connect("http://www.baidu.com").get();
		
		//获取 body
		Element body = document.body();
		
		//这句话翻译过来就是  body里的 id=u1的div中 a标签含有href的 Elements 
		//大家可自行百度 Jsoup 和 Document 的 API 里面写的不能再详细了
        Elements select = body.select("div[id=u1]").select( "a[href]");
        
        //获取Elements 中的 text
        String text = select.text();
        System.out.println(text);

数据已经爬出来了,大功告成!
在这里插入图片描述
在这里插入图片描述
附源码

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

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

public class RequestAndResponseTool {
	
	/**第二种简便方式获取*/
    public static void main(String[] args) throws Exception {
        Document document = Jsoup.connect("http://www.baidu.com").get();
        Element body = document.body();
        Elements select = body.select("div[id=u1]").select( "a[href]");
        String text = select.text();
        //打印数据
        System.out.println(text);
    }
    
	/**第一种原始方式获取*/
    public Object sendRequest() throws Exception {
        //定义请求 URL 这里用百度举例
        URL url = new URL("http://www.baidu.com");
        //实例化对象,官方文档就是用这个方式实例化 HttpURLConnection
        HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
        httpURLConnection.setConnectTimeout(1000);
        httpURLConnection.setReadTimeout(2000);
        //确认成功与否
        if (httpURLConnection.getResponseCode() == 200){
            //获取输入流
            InputStream inputStream = httpURLConnection.getInputStream();
            //获取 html 页面
            String html = convertStreamToString(inputStream);
            //拿到 Document
            Document document = Jsoup.parse(html);
            Element body = document.body();
            Elements select = body.select("div[id=u1]").select( "a[href]");
            //打印数据
            String text = select.text();
            System.out.println(text);
        }
        return null;
    }


    /**这个方法是将InputStream转化为String*/
    public static String convertStreamToString(InputStream is) throws IOException {
        if (is == null){
            return "";
        }
        BufferedReader reader = new BufferedReader(new InputStreamReader(is,"utf8"));
        StringBuilder sb = new StringBuilder();
        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        reader.close();
        return sb.toString();
    }

}

  • 2
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值