简单的爬虫案例

由 Toniko 创建, 最后一次修改 2019-07-08

简单的爬虫案例: 将百度的首页爬取下来并保存在文件中。

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.URL;

public class Test {
    public static void main(String[] args) throws UnsupportedEncodingException, IOException {
        URL url = new URL("http://www.baidu.com");
        BufferedReader bReader = 
                new BufferedReader(new InputStreamReader(url.openStream(), "utf-8"));
        BufferedWriter bWriter = 
                new BufferedWriter(new OutputStreamWriter(new FileOutputStream("baidu.html")));
        String msg = null;
        while((msg = bReader.readLine()) != null) {
//          System.out.println(msg);
            bWriter.append(msg + "\n");
        }
        bWriter.close();
        bReader.close();
    }
}
以上内容是否对您有帮助:
二维码
建议反馈
二维码