java爬取网页并保存_Java-爬取网页并且保存的方法

本文介绍了如何使用Java的UrlConnection和HttpClient库来爬取网页内容,并将其保存到本地文件。通过示例代码详细展示了两种方法的实现过程,包括解决中文乱码问题。对于Java开发者来说,这是掌握网页抓取技术的基础教程。
摘要由CSDN通过智能技术生成

网络爬虫是自动提取网页的程序,它是搜索引擎的重要组成部分,传统的爬虫程序从初始网页到多个URL,在对网页进行爬行的过程中,它不断地从当前网页中提取新的URL并将其放入队列中,一起跟着爱站技术频道小编来看看Java-爬取网页并且保存的方法吧!

UrlConnection爬取实现

package html;

import java.io.BufferedReader;

import java.io.FileOutputStream;

import java.io.FileWriter;

import java.io.IOException;

import java.io.InputStream;

import java.io.InputStreamReader;

import java.io.OutputStreamWriter;

import java.net.MalformedURLException;

import java.net.URL;

import java.net.URLConnection;

public class Spider {

public static void main(String[] args) {

String filepath = "d:/124.html";

String url_str = "http://www.hao123.com/";

URL url = null;

try {

url = new URL(url_str);

} catch (MalformedURLException e) {

e.printStackTrace();

}

String charset = "utf-8";

int sec_cont = 1000;

try {

URLConnection url_con = url.openConnection();

url_con.setDoOutput(true);

url_con.setReadTimeout(10 * sec_cont);

url_con.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)");

InputStream htm_in = url_con.getInputStream();

String htm_str = InputStream2String(htm_in,charset);

saveHtml(filepath,htm_str);

} catch (IOException e) {

e.printStackTrace();

}

}

/**

* Method: saveHtml

* Description: save String to file

* @param filepath

* file path which need to be saved

* @param str

* string saved

*/

public static void saveHtml(String filepath, String str){

try {

/*@SuppressWarnings("resource")

FileWriter fw = new FileWriter(filepath);

fw.write(str);

fw.flush();*/

OutputStreamWriter outs = new OutputStreamWriter(new FileOutputStream(filepath, true), "utf-8");

outs.write(str);

System.out.print(str);

outs.close();

} catch (IOException e) {

System.out.println("Error at save html...");

e.printStackTrace();

}

}

/**

* Method: InputStream2String

* Description: make InputStream to String

* @param in_st

* inputstream which need to be converted

* @param charset

* encoder of value

* @throws IOException

* if an error occurred

*/

public static String InputStream2String(InputStream in_st,String charset) throws IOException{

BufferedReader buff = new BufferedReader(new InputStreamReader(in_st, charset));

StringBuffer res = new StringBuffer();

String line = "";

while((line = buff.readLine()) != null){

res.append(line);

}

return res.toString();

}

}

实现过程中,爬取的网页的中文乱码问题,是个比较麻烦的事情。

HttpClient爬取实现

HttpClient实现爬取网页时,遇到了很多问题。其一,就是存在两个版本的HttpClient,一个是sun内置的,另一个是apache开源的一个项目,似乎sun内置用的不太多,我也就没有实现,而是采用了apache开源项目(以后说的HttpClient都是指apache的开源版本);其二,在使用HttpClient时,最新的版本已经不同于以前的版本,从HttpClient4.x版本后,导入的包就已经不一样了,从网上找的很多部分都是HttpClient3.x版本的,所以如果使用最新的版本,还是看帮助文件为好。

我用的是Eclipse,需要配置环境导入引用包。

首先,下载HttpClient,地址是:http://hc.apache.org/downloads.cgi,我是用的事HttpClient4.2版本。

然后,解压缩,找到了/lib文件夹下的commons-codec-1.6.jar,commons-logging-1.1.1.jar,httpclient-4.2.5.jar,httpcore-4.2.4.jar(版本号根据下载的版本有所不同,还有其他的jar文件,我这里暂时用不到,所以先导入必须的);

最后,将上面的jar文件,加入classpath中,即右击工程文件 => Bulid Path => Configure Build Path => Add External Jar..,然后添加上面的包就可以了。

还用一种方法就是讲上面的包,直接复制到工程文件夹下的lib文件夹中。

下面是实现代码:

package html;

import java.io.BufferedReader;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.InputStream;

import java.io.InputStreamReader;

import java.io.OutputStreamWriter;

import org.apache.http.HttpEntity;

import org.apache.http.HttpResponse;

import org.apache.http.client.*;

import org.apache.http.client.methods.HttpGet;

import org.apache.http.impl.client.DefaultHttpClient;

public class SpiderHttpClient {

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

// TODO Auto-generated method stub

String url_str = "http://www.hao123.com";

String charset = "utf-8";

String filepath = "d:/125.html";

HttpClient hc = new DefaultHttpClient();

HttpGet hg = new HttpGet(url_str);

HttpResponse response = hc.execute(hg);

HttpEntity entity = response.getEntity();

InputStream htm_in = null;

if(entity != null){

System.out.println(entity.getContentLength());

htm_in = entity.getContent();

String htm_str = InputStream2String(htm_in,charset);

saveHtml(filepath,htm_str);

}

}

/**

* Method: saveHtml

* Description: save String to file

* @param filepath

* file path which need to be saved

* @param str

* string saved

*/

public static void saveHtml(String filepath, String str){

try {

/*@SuppressWarnings("resource")

FileWriter fw = new FileWriter(filepath);

fw.write(str);

fw.flush();*/

OutputStreamWriter outs = new OutputStreamWriter(new FileOutputStream(filepath, true), "utf-8");

outs.write(str);

outs.close();

} catch (IOException e) {

System.out.println("Error at save html...");

e.printStackTrace();

}

}

/**

* Method: InputStream2String

* Description: make InputStream to String

* @param in_st

* inputstream which need to be converted

* @param charset

* encoder of value

* @throws IOException

* if an error occurred

*/

public static String InputStream2String(InputStream in_st,String charset) throws IOException{

BufferedReader buff = new BufferedReader(new InputStreamReader(in_st, charset));

StringBuffer res = new StringBuffer();

String line = "";

while((line = buff.readLine()) != null){

res.append(line);

}

return res.toString();

}

}

以上便是关于Java-爬取网页并且保存的方法介绍,只有对各个编程都有所了解才能选择是否真的适合自己,要知道今天的程序员已经和以前不一样了。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值