当前位置: 移动技术网 > IT编程>开发语言>Java > 详解Java两种方式简单实现:爬取网页并且保存

详解Java两种方式简单实现:爬取网页并且保存

2019年07月22日  | 移动技术网IT编程  | 我要评论

对于网络,我一直处于好奇的态度。以前一直想着写个爬虫,但是一拖再拖,懒得实现,感觉这是一个很麻烦的事情,出现个小错误,就要调试很多时间,太浪费时间。

后来一想,既然早早给自己下了保证,就先实现它吧,从简单开始,慢慢增加功能,有时间就实现一个,并且随时优化代码。

下面是我简单实现爬取指定网页,并且保存的简单实现,其实有几种方式可以实现,这里慢慢添加该功能的几种实现方式。

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,地址是:,我是用的事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();
  }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网