Java爬虫入门——HttpClient,JSoup

一,网络爬虫介绍

爬虫也叫网络机器人,可以代替人工,自动的在网络上采集和处理信息。

爬虫包括数据采集,分析,存储三部

爬虫引入依赖

<!--引入httpClient依赖-->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.14</version>
        </dependency>

二,入门程序

   public static void main(String[] args) throws IOException {

        //1,打开浏览器,创建HttpClient对象
        CloseableHttpClient client = HttpClients.createDefault();

        //2,输入网址,发起HttpGet请求
        HttpGet httpGet = new HttpGet("http://www.baidu.cn");

        //3,按回车,发起请求,使用Httpclient对象发起请求
        CloseableHttpResponse response = client.execute(httpGet);

        //4,解析响应,获取数据
        if (response.getStatusLine().getStatusCode() == 200){//获取响应数据的状态码
            HttpEntity entity = response.getEntity();//获取响应体
            String content = EntityUtils.toString(entity,"utf8");//获取静态页面
            System.out.println(content);
        }

获取到百度首页的前端页面

三,HttpClient请求

一),使用Http协议客户端HttpClient这个技术,抓取网页数据。

二),Get请求

1,不带参数的get请求,获取静态页面的行数

 public static void main(String[] args) throws IOException {
        //创建HttpGet对象
        HttpGet httpGet = new HttpGet("http://www.itcast.com");
        //创建HttpClient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        try {
            //使用HttpClient对象发起请求,获取response
            response = httpClient.execute(httpGet);
            //解析响应
            if (response.getStatusLine().getStatusCode() == 200){
                String content = EntityUtils.toString(response.getEntity(), "utf8");
                System.out.println(content.length());
            }
        } catch (IOException e) {


        }finally {
            response.close();
            httpClient.close();
        }
    }

2,带参数的HttpGet请求

    public static void main(String[] args) throws Exception {
        //建立URIBuilder请求的路径
        URIBuilder uriBuilder = new URIBuilder("http://www.baidu.com/s");
        uriBuilder.setParameter("wd","狂飙")
                .setParameter("rsv_spt","1");//设置参数

        //建立该路径下的Get请求
        HttpGet httpGet = new HttpGet(uriBuilder.build());
        System.out.println("发起请求的信息:" + httpGet);
        //创建HttpClient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        try {
            //使用HttpClient对象发起请求,获取response
            response = httpClient.execute(httpGet);
            System.out.println("响应状态码"+response.getStatusLine().getStatusCode());
            //解析响应
            if (response.getStatusLine().getStatusCode() == 200){
                String content = EntityUtils.toString(response.getEntity(), "utf8");
                System.out.println("响应体长度:" + content.length());
            }
        } catch (IOException e) {
            
        }finally {
            response.close();
            httpClient.close();
        }
    }

三),Post请求

1,不带参数的HttpPost请求

public static void main(String[] args)  {
        //创建HttpClient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();

        //创建HttpPost对象
        HttpPost httpPost = new HttpPost("http://www.baidu.com");
        System.out.println("发起请求信息"+httpPost);
        CloseableHttpResponse response = null;
        //获取响应
        try {
            response = httpClient.execute(httpPost);
            System.out.println("响应状态码:" + response.getStatusLine().getStatusCode());
            String content = EntityUtils.toString(response.getEntity());
            System.out.println("响应数据长度:"+content.length());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            try {
                httpClient.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

    }

2,带参数的HttpPost请求

    public static void main(String[] args) throws UnsupportedEncodingException {
        //创建HttpClient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();

        //创建HttpPost对象
        HttpPost httpPost = new HttpPost("http://www.baidu.com");
        System.out.println("发起请求信息"+httpPost);

        //设置List集合,用来存放请求的参数
        List<NameValuePair> params = new ArrayList<>();
        //添加请求参数
        params.add(new BasicNameValuePair("wd","狂飙"));
        //创建Entity对象,构造方法中,一个是请求参数集合,一个是字符集编码
        UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(params,"utf8");
        //设置表单的Entity对象到Post请求中
        httpPost.setEntity(formEntity);
        
        CloseableHttpResponse response = null;
        //获取响应
        try {
            response = httpClient.execute(httpPost);
            System.out.println("响应状态码:" + response.getStatusLine().getStatusCode());
            String content = EntityUtils.toString(response.getEntity());
            System.out.println("响应数据长度:"+content.length());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            try {
                httpClient.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

    }

四,HttpClient连接池

public static void main(String[] args) {
        //创建httpClient连接池管理对象
        PoolingHttpClientConnectionManager manager = new PoolingHttpClientConnectionManager();
        //设置连接池最大连接数量
        manager.setMaxTotal(100);
        //设置本机访问每个url时,最多分配10个httpClient对象访问
        manager.setDefaultMaxPerRoute(10);
        
        doGet(manager);
        doGet(manager);
    }
    public static void  doGet(PoolingHttpClientConnectionManager manager) {
        //从连接池中获取httpClient对象
        CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(manager).build();
        CloseableHttpResponse response = null;
        try {
            //设置请求路径和参数
            URIBuilder uriBuilder = new URIBuilder("http://www.baidu.com/s");
            uriBuilder.setParameter("wd","狂飙");

            //创建HttpGet请求
            HttpGet httpGet = new HttpGet(uriBuilder.build());
            System.out.println("请求头:" + httpGet);
            //发起请求

            response = httpClient.execute(httpGet);

            //解析请求
            if (response.getStatusLine().getStatusCode() == 200){
                HttpEntity entity = response.getEntity();
                String content = EntityUtils.toString(entity);
                System.out.println("响应数据的长度:"+content.length());
            }
        }catch (Exception w){

        }finally {
            try {
                response.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            //httpClient不能手动关闭,因为交给了连接管理
        }
    }

五,请求参数

因为网络或者服务器的原因,需要设置一些参数,确保访问快速,正常!

        //创建HttpGet对象
        HttpGet httpGet = new HttpGet("http://www.baidu.com");
        
        //设置HttpClient请求参数
        RequestConfig config = RequestConfig.custom().setConnectTimeout(1000)//设置连接创建最大时间
                .setConnectionRequestTimeout(1000)//设置获取连接最大时间,单位ms
                .setSocketTimeout(10 * 1000) //设置数据传输最大时间
                .build();
        
        httpGet.setConfig(config);//将配置设置到get请求中

六,Jsoup

Jsoup是专门解析html的技术,是一款Java的html解析器

可以直接解析url地址、Html文本内容,提供了非常省力的API,课通过DOM,CSS以及类似于JQuery的操作方法来取出和操作数据。

主要功能:

1,从一个url,文件或字符串中解析html

2,使用DOM,CSS选择器来查找,取出数据

3,可操作HTML元素,熟悉,文本;

Jsoup依赖:

        <dependency>
            <groupId>org.jsoup</groupId>
            <artifactId>jsoup</artifactId>
            <version>1.10.2</version>
        </dependency>

引入IO工具类依赖

<!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.6</version>
</dependency>

引入字符串工具类

<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.7</version>
</dependency>

一),Jsoup解析url

    @Test
    public void testURL() throws Exception{
        //Jsoup解析url地址,获取百度首页标题,超时时间1000ms
        Document document = Jsoup.parse(new URL("http://www.baidu.com"), 1000);
        String title = document.getElementsByTag("title").first().text();
        System.out.println(title);
    }

二),Jsoup解析字符串

 @Test
    public void testString() throws Exception{
        //将文件转换成字符串
        String fileToString = FileUtils.readFileToString(new File(""), "utf8");
        //使用Jsoup解析字符串
        Document document = Jsoup.parse(fileToString);
        //获取title标签
        Element title = document.getElementsByTag("title").first();
        System.out.println(title.text());
    }

三),Jsoup解析文件

    @Test
    public void testFile() throws Exception{
        Document document = Jsoup.parse(new File(""), "utf8");
        Element title = document.getElementsByTag("title").first();
        System.out.println(title.text());
    }

四),使用dom方式遍历文档

    @Test
    public void testDOM() throws Exception{
        //获取dom对象
        Document document = Jsoup.parse("http://www.baidu.com/");

        //解析
        Elements title = document.getElementsByTag("title");//通过标签获取元素
        Element elementById = document.getElementById("s_menu_mine");//通过id获取元素
        document.getElementsByAttribute("属性名");//通过属性获取元素
        document.getElementsByAttributeValue("href","value");
        document.getElementsByClass("类名");//通过类获取元素
    }

五),从元素中获取数据

    @Test
    public void testData() throws Exception{
        Document document = Jsoup.parse("http://www.baidu.com/");
        Element element = document.getElementById("kw");
        element.id();//获取元素id
        element.text();//获取文本内容
        element.className();//获取元素的class
        element.attributes();//从元素中获取所有属性的值
        element.attr("class");//从元素获取属性的值
        element.select("span");//通过搜索span标签获取Element
        element.select("#id");//通过搜索id标签获取Element
        element.select(".class");//通过搜索class标签获取Element
        element.select("[name]");//通过搜索属性获取Element
        element.select("[class=class_a]");//通过属性的值获取Element
    }

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要使用Java编写基于HttpClientJsoup爬虫,需要进行以下步骤: 1. 首先,导入HttpClientJsoup的依赖包。可以使用maven或gradle进行依赖管理。 2. 创建一个HttpClient实例,用于发送HTTP请求和接收响应。可以使用HttpClients.createDefault()方法创建一个默认配置的实例。 3. 创建一个HttpGet实例,设置请求URL和请求头信息。可以使用new HttpGet(url)方法创建一个HttpGet实例,然后使用setHeader()方法设置请求头信息。 4. 发送HTTP请求,并获取响应结果。可以使用HttpClient.execute()方法发送请求,并使用HttpResponse.getEntity()方法获取响应实体。 5. 解析HTML内容。可以使用Jsoup.parse()方法解析HTML内容,然后使用Jsoup提供的API进行内容提取和处理。 以下是一个使用HttpClientJsoup进行网页爬取的示例代码: ```java import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import java.io.IOException; public class WebCrawler { public static void main(String[] args) throws IOException { // 创建一个HttpClient实例 HttpClient httpClient = HttpClients.createDefault(); // 创建一个HttpGet实例,设置请求URL和请求头信息 HttpGet httpGet = new HttpGet("https://www.example.com"); httpGet.setHeader("User-Agent", "Mozilla/5.0"); // 发送HTTP请求,并获取响应结果 HttpResponse httpResponse = httpClient.execute(httpGet); String html = EntityUtils.toString(httpResponse.getEntity(), "UTF-8"); // 解析HTML内容 Document document = Jsoup.parse(html); String title = document.title(); System.out.println("Title: " + title); } } ``` 在这个示例中,我们使用HttpClient发送了一个GET请求到https://www.example.com,并获取了响应结果。然后使用Jsoup解析HTML内容,并获取了网页的标题。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值