【知识积累】使用Httpclient实现网页的爬取并保存至本地

程序功能实现了爬取网页页面并且将结果保存到本地,通过以爬取页面出发,做一个小的爬虫,分析出有利于自己的信息,做定制化的处理。

其中需要的http*的jar文件,可以在网上自行下载

复制代码
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

public class CrawlPage {
    private static String filePath = "F:\\01_Code\\01_Eclipse\\AnalogLogin\\crawData\\";
    private static String url = "http://www.huxiu.com/";
    private static void saveToLocal(InputStream in, String filePath, String filename) throws IOException {
        File file = new File(filePath);
        if(!file.exists())
            file.mkdirs();
        DataOutputStream out = new DataOutputStream(new FileOutputStream(
                new File(filePath + filename)));
        int result;
        while((result=in.read())!=-1){
            out.write(result);
        }
        out.flush();
        out.close();
    }
    
    public static void crawlPage() throws IOException {
         DefaultHttpClient client = new DefaultHttpClient();
         HttpGet get = new HttpGet(url);
         HttpResponse response = client.execute(get);
         HttpEntity entity = response.getEntity();
         InputStream in = entity.getContent();
         String fileName = "crawlPage.html";
         //保存到本地
         saveToLocal(in, filePath + url.substring(5) + "\\", fileName);
    }
    
    public static void main(String[] args) throws IOException {
        crawlPage();
    }
}
复制代码

 

posted @   leesf  阅读(3856)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!

喜欢请打赏

扫描二维码打赏

了解更多

点击右上角即可分享
微信分享提示