java抓取页面内容,代码和详解步骤

 在做项目或要利用其他网站内容进行数据收集或分析时,想为我所用,通常需要分三步:

1、将目标页面进行爬取,获取原内容;

2、根据爬取的内容,进行分析规律,然后进行分解提取,获取想要的数据内容和格式;

3、基于内容和格式,做后续的分析和事情


1、Java代码-----将目标页面进行爬取,获取原内容;

import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.HttpClientUtils;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import java.io.IOException;

public class getContentbyUrl{

    public static void main(String[] args) {
    //1.创建httpclient(相当于打开一个浏览器)
    CloseableHttpClient httpClient = HttpClients.createDefault();
    

    //2.创建get请求(相当于浏览器输入网址)
    HttpGet request = new HttpGet("www.baidu.com");

    CloseableHttpResponse response = null;
    try {
        //3.执行get请求(相当于输入网址后敲回车键)
        response = httpClient.execute(request);

        //4.判断响应状态是否为200
        if(response.getStatusLine().getStatusCode() == org.apache.http.HttpStatus.SC_OK){
            
            //5.获取响应内容即页面内容
            org.apache.http.HttpEntity httpEntity = response.getEntity();
            String html = org.apache.http.util.EntityUtils.toString(httpEntity, "utf-8");

            //打印出来
            System.out.println(html);
        } else {
            //如果返回状态不是200,比如404(页面不存在)等
            System.out.println("返回状态不是200");                
            System.out.println(EntityUtils.toString(response.getEntity(), "utf-8"));
        }
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        //6.关闭
        HttpClientUtils.closeQuietly(response);
        HttpClientUtils.closeQuietly(httpClient);
    }
}
}

2、根据上面获得的内容,进行分解提取;

这一步,需要根据目标页面和获取内容不同,通过正则表达式去分解提取页面里自己想要的元素。

//对html,进行截取,从 “data":[ 之后开始
String gpString = html.substring(html.indexOf("\"data\":[")+8,html.indexOf("],\"error\":null}"));

//以 },为分割获取对应的数组数据
String[] gpStrings= gpString.split("},");

java.util.List<orgs> list = new java.util.ArrayList();

for(int i=0;i< gpStrings.length;i++){
    String temp = gpStrings[i].substring(1).replace("{","");
    String[] temps = temp.split("\",");
    orgs ors = new orgs();
    if(temps.length > 2){                                                
       ors.setGpCode(temps[1].substring(temps[1].indexOf(":\"")+2));                    
       ors.setGpName(temps[2].substring(temps[2].indexOf(":\"")+2));
    }

    list.add(ors);
}

3、基于内容和格式,做后续的分析和事情

 这一步就要根据自己要做的事情而定了

 


版权声明:本文为ydjianchou原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。