Java 实例 - 网页抓取

Java 教程 · 2019-02-11 21:44:09

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

Main.java 文件

import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.InputStreamReader; import java.net.URL; public class Main { public static void main(String[] args) throws Exception { URL url = new URL("http://www.codercto.com"); BufferedReader reader = new BufferedReader (new InputStreamReader(url.openStream())); BufferedWriter writer = new BufferedWriter (new FileWriter("data.html")); String line; while ((line = reader.readLine()) != null) { System.out.println(line); writer.write(line); writer.newLine(); } reader.close(); writer.close(); } }

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

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

点击查看所有 Java 教程 文章: https://www.codercto.com/courses/l/12.html

查看所有标签

Defensive Design for the Web

Defensive Design for the Web

37signals、Matthew Linderman、Jason Fried / New Riders / 2004-3-2 / GBP 18.99

Let's admit it: Things will go wrong online. No matter how carefully you design a site, no matter how much testing you do, customers still encounter problems. So how do you handle these inevitable bre......一起来看看 《Defensive Design for the Web》 这本书的介绍吧!

XML、JSON 在线转换
XML、JSON 在线转换

在线XML、JSON转换工具

Markdown 在线编辑器
Markdown 在线编辑器

Markdown 在线编辑器

UNIX 时间戳转换
UNIX 时间戳转换

UNIX 时间戳转换