如何在不使用任何外部函数库的情况下读取 Java 中网页内容?
java.net 包的 URL 类表示统一资源定位器,用于指向万维网中的资源(文件或目录或引用)。
此类的 openStream() 方法打开指向当前对象表示的 URL 的连接,并返回一个 InputStream 对象,您可以使用该对象从 URL 中读取数据。
因此,要从网页中读取数据(使用 URL 类)-
通过将所需网页的 URL 作为其构造函数的参数传入,实例化 java.net.URL 类。
调用 openStream() 方法并检索 InputStream 对象。
通过将以上检索的 InputStream 对象作为参数,实例化 Scanner 类。
示例
import java.io.IOException;
import java.net.URL;
import java.util.Scanner;
public class ReadingWebPage {
public static void main(String args[]) throws IOException {
//Instantiating the URL class
URL url = new URL("http://www.something.com/");
//Retrieving the contents of the specified page
Scanner sc = new Scanner(url.openStream());
//Instantiating the StringBuffer class to hold the result
StringBuffer sb = new StringBuffer();
while(sc.hasNext()) {
sb.append(sc.next());
//System.out.println(sc.next());
}
//Retrieving the String from the String Buffer object
String result = sb.toString();
System.out.println(result);
//Removing the HTML tags
result = result.replaceAll("<[^>]*>", "");
System.out.println("Contents of the web page: "+result);
}
}输出
<html><body><h1>Itworks!</h1></body></html> Contents of the web page: Itworks!
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP