一、使用 HttpClient 抓取网页数据

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
public String getHtml(String htmlurl) throws IOException {
        StringBuffer sb = new StringBuffer();
        String acceptEncoding = "";
        /* 1.生成 HttpClinet 对象并设置参数 */
        HttpClient httpClient = new HttpClient();
        GetMethod method = new GetMethod(htmlurl);
        int statusCode;
        try {
            statusCode = httpClient.executeMethod(method);
            // 判断访问的状态码
            if (statusCode != HttpStatus.SC_OK) {
                return null;
            else {
                if (method.getResponseHeader("Content-Encoding") != null)
                    acceptEncoding = method.getResponseHeader(
                            "Content-Encoding").getValue();
                if (acceptEncoding.toLowerCase().indexOf("gzip") > -1) {
                    // 建立gzip解压工作流
                    InputStream is;
                    is = method.getResponseBodyAsStream();
                    GZIPInputStream gzin = new GZIPInputStream(is);
                    InputStreamReader isr = new InputStreamReader(gzin, Charset.forName(CHARSET)); // 设置读取流的编码格式,自定义编码
                    java.io.BufferedReader br = new java.io.BufferedReader(isr);
                    String tempbf;
                    while ((tempbf = br.readLine()) != null) {
                        if(StringUtils.isNotBlank(tempbf)){
                            sb.append(tempbf);
                        }
                    }
                    isr.close();
                    gzin.close();
                    System.out.println(sb);
                else {
                    InputStreamReader isr;
                    isr = new InputStreamReader(
                            method.getResponseBodyAsStream(), CHARSET);
                    java.io.BufferedReader br = new java.io.BufferedReader(isr);
                    String tempbf;
                    while ((tempbf = br.readLine()) != null) {
                        if(StringUtils.isNotBlank(tempbf)){
                            sb.append(tempbf);
                        }
                    }
                    isr.close();
                }
            }
        catch (HttpException e) {
            e.printStackTrace();
        catch (IOException e) {
            e.printStackTrace();
        }
        method.abort();
        method.releaseConnection();
        return sb.toString();
    }

二、使用HttpPost抓取网页数据

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
private static CloseableHttpClient httpClient;
    private static BasicHttpContext httpContext;
    private static BasicCookieStore cookieStore;
    private static PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
    private static RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.BEST_MATCH).build();
    private static RequestConfig localConfig = RequestConfig.copy(globalConfig).setCookieSpec(CookieSpecs.BROWSER_COMPATIBILITY).build();
 
public String getHtml(String url){
        HttpClientBuilder builder = HttpClients.custom();
        cookieStore = new BasicCookieStore();
        builder.setConnectionManager(cm);
        builder.setDefaultCookieStore(cookieStore);
        builder.setDefaultRequestConfig(globalConfig);
        httpClient = builder.build();
        httpContext = new BasicHttpContext();
        httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
        HttpPost httpPost = new HttpPost(url);
        httpPost.setConfig(localConfig);
        httpPost.setHeader("Accept""text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
        httpPost.setHeader("Accept-Encoding","gzip, deflate");
        httpPost.setHeader("Accept-Language","zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3");
        httpPost.setHeader("Connection","keep-alive");
        httpPost.setHeader("Cookie","ASP.NET_SessionId=11vrr4ucwsgeqtmpyfx4hmvx; _5t_trace_sid=89c4ffb8633d267e4ae322a157b52471; _5t_trace_tms=1; CheckCode=X0P64");
        httpPost.setHeader("User-Agent","Mozilla/5.0 (Windows NT 6.1; WOW64; rv:39.0) Gecko/20100101 Firefox/39.0");
         List <NameValuePair> nvps = new ArrayList <NameValuePair>();
            nvps.add(new BasicNameValuePair("pid""99-C3-57-35-6D-70-3D-F2"));
            nvps.add(new BasicNameValuePair("CurrentlyPageIndex""2"));
            httpPost.setEntity(new UrlEncodedFormEntity(nvps, Consts.UTF_8));
        try {
            CloseableHttpResponse response = httpClient.execute(httpPost,httpContext);
            int status = response.getStatusLine().getStatusCode();
            if (status >= 200 && status < 300) {
                HttpEntity httpEntity = response.getEntity();
                if(httpEntity!=null){
                    String cont = trimLineToString(httpEntity, "UTF-8");
                    EntityUtils.consume(httpEntity);
                    return cont;
                }
            }
        catch (ClientProtocolException e) {
            e.printStackTrace();
        catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
         
    public synchronized static String trimLineToString(HttpEntity entiry,String charset) {
 
        StringBuffer sb = new StringBuffer();
        BufferedReader reader = null;
        try {
            InputStream instream = entiry.getContent();
            reader = new BufferedReader(new InputStreamReader(instream, charset));
            String str = null;
            while ((str = reader.readLine()) != null) {
                if(StringUtils.isNotBlank(str)) {
                    sb.append(str.trim());
                }
            }
            instream.close();
        catch (IllegalStateException e) {
            e.printStackTrace();
        catch (IOException e) {
            e.printStackTrace();
        finally {
            if (reader != null) {
                try {
                    reader.close();
                catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return sb.toString();
    }

使用JAVA抓取网页数据的更多相关文章

  1. java抓取网页数据,登录之后抓取数据。

    最近做了一个从网络上抓取数据的一个小程序.主要关于信贷方面,收集的一些黑名单网站,从该网站上抓取到自己系统中. 也找了一些资料,觉得没有一个很好的,全面的例子.因此在这里做个笔记提醒自己. 首先需要一 ...

  2. Java抓取网页数据(原网页+Javascript返回数据)

    有时候由于种种原因,我们需要采集某个网站的数据,但由于不同网站对数据的显示方式略有不同! 本文就用Java给大家演示如何抓取网站的数据:(1)抓取原网页数据:(2)抓取网页Javascript返回的数 ...

  3. Java抓取网页数据(原来的页面+Javascript返回数据)

    转载请注明出处! 原文链接:http://blog.csdn.net/zgyulongfei/article/details/7909006 有时候因为种种原因,我们须要採集某个站点的数据,但因为不同 ...

  4. Java抓取网页数据

    http://ayang1588.github.io/blog/2013/04/08/catchdata/ 最近处于离职状态,正赶清闲,开始着手自己的毕业设计,课题定的是JavaWeb购物平台,打算用 ...

  5. Jsoup一个简短的引论——采用Java抓取网页数据

    转载请注明出处:http://blog.csdn.net/allen315410/article/details/40115479 概述 jsoup 是一款Java 的HTML解析器,可直接解析某个U ...

  6. 01 UIPath抓取网页数据并导出Excel(非Table表单)

    上次转载了一篇<UIPath抓取网页数据并导出Excel>的文章,因为那个导出的是table标签中的数据,所以相对比较简单.现实的网页中,有许多不是通过table标签展示的,那又该如何处理 ...

  7. Asp.net 使用正则和网络编程抓取网页数据(有用)

    Asp.net 使用正则和网络编程抓取网页数据(有用) Asp.net 使用正则和网络编程抓取网页数据(有用) /// <summary> /// 抓取网页对应内容 /// </su ...

  8. 使用HtmlAgilityPack批量抓取网页数据

    原文:使用HtmlAgilityPack批量抓取网页数据 相关软件点击下载登录的处理.因为有些网页数据需要登陆后才能提取.这里要使用ieHTTPHeaders来提取登录时的提交信息.抓取网页  Htm ...

  9. web scraper 抓取网页数据的几个常见问题

    如果你想抓取数据,又懒得写代码了,可以试试 web scraper 抓取数据. 相关文章: 最简单的数据抓取教程,人人都用得上 web scraper 进阶教程,人人都用得上 如果你在使用 web s ...

随机推荐

  1. Inside Geometry Instancing(下)

    Inside Geometry Instancing(下) http://blog.csdn.net/soilwork/article/details/655858 此教程版权归我所有,仅供个人学习使 ...

  2. Unity Prefabs

    通过上一期的学习,我们知道为了如何向场景中添加一个物体.问题来了,如果需要对这个立方体进行修改应该怎么做呢?那我们肯定就得修改这段代码,能不能将立方体本身从我们的开发中单独提出来呢?这就涉及到我们今天 ...

  3. 分布式集群环境下,如何实现session共享五(spring-session+redis 实现session共享)

    这是分布式集群环境下,如何实现session共享系列的第五篇.在上一篇:分布式集群环境下,如何实现session共享四(部署项目测试)中,针对nginx不同的负载均衡策略:轮询.ip_hash方式,测 ...

  4. "字节跳动杯"2018中国大学生程序设计竞赛-女生专场

    口算训练 #include <iostream> #include <algorithm> #include <cstring> #include <cstd ...

  5. python操作redis之hash操作

    # __author__ = 'STEVEN' import redis,time #连接池 polls = redis.ConnectionPool(host='192.168.43.22',por ...

  6. bzoj 4597||洛谷P4340 [Shoi2016]随机序列

    https://www.lydsy.com/JudgeOnline/problem.php?id=4597 https://www.luogu.org/problemnew/show/P4340 妄图 ...

  7. C语言的面向对象技术

    引言:面向过程的C有效率高,代码紧凑的特点,在单片机嵌入式领域是C的主要阵地,while(1)+中断是其主要的开发模式,但是当系统复杂到一定程度,想要添加一个功能需要改动很多地方,耦合性太强:跟别人交 ...

  8. 编写可执行程序,其它程序调用,并返回数据,C#

    有时候在创建临时文件或文件夹,使用完成后,释放失败,删除提示占用,又不能结束主程序,就可以通过别的方法来解决 比如,另外创建一个程序,单独执行任务,完成后结束程序,并返回执行结果,上述问题就能解决. ...

  9. 第七章 设计程序架构 之 设计HTTP模块和处理程序

    1. 概述 HTTP模块和处理程序,可以让程序员直接跟HTTP请求交互. 本章内容包括 实现同步和异步模块及处理程序以及在IIS中如何选择模块和处理程序. 2. 主要内容 2.1 实现同步和异步模块及 ...

  10. HashMap之put方法流程解读

    说明:本文中所谈论的HashMap基于JDK 1.8版本源码进行分析和说明. HashMap的put方法算是HashMap中比较核心的功能了,复杂程度高但是算法巧妙,同时在上一版本的基础之上优化了存储 ...