Java 实例 - 网页抓取

以下实例演示了如何使用 net.URL 类的 URL() 构造函数来抓取网页:

Main.java 文件

  1. import java.io.BufferedReader;
  2. import java.io.BufferedWriter;
  3. import java.io.FileWriter;
  4. import java.io.InputStreamReader;
  5. import java.net.URL;
  6. public class Main {
  7. public static void main(String[] args)
  8. throws Exception {
  9. URL url = new URL("http://www.baidu.com");
  10. BufferedReader reader = new BufferedReader
  11. (new InputStreamReader(url.openStream()));
  12. BufferedWriter writer = new BufferedWriter
  13. (new FileWriter("data.html"));
  14. String line;
  15. while ((line = reader.readLine()) != null) {
  16. System.out.println(line);
  17. writer.write(line);
  18. writer.newLine();
  19. }
  20. reader.close();
  21. writer.close();
  22. }
  23. }

以上代码运行输出结果为(网页的源代码,存储在当前目录下的 data.html 文件中):

  1. <!DOCTYPE html> <html> <head> <meta charset="UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=11,IE=10,IE=9,IE=8"/>……