33

在不使用任何外部库的情况下,将网站的 HTML 内容提取到字符串中的最简单方法是什么?

4

5 回答 5

44

我目前正在使用这个:

String content = null;
URLConnection connection = null;
try {
  connection =  new URL("http://www.google.com").openConnection();
  Scanner scanner = new Scanner(connection.getInputStream());
  scanner.useDelimiter("\\Z");
  content = scanner.next();
  scanner.close();
}catch ( Exception ex ) {
    ex.printStackTrace();
}
System.out.println(content);

但不确定是否有更好的方法。

于 2008-08-28T01:21:00.797 回答
21

这对我来说效果很好:

URL url = new URL(theURL);
InputStream is = url.openStream();
int ptr = 0;
StringBuffer buffer = new StringBuffer();
while ((ptr = is.read()) != -1) {
    buffer.append((char)ptr);
}

不确定提供的其他解决方案是否更有效。

于 2008-08-29T05:11:10.500 回答
2

我刚刚把这篇文章留在了你的另一个帖子中,尽管你上面的内容也可能有用。我认为任何一个都不会比另一个更容易。import org.apache.commons.HttpClient只需在代码顶部使用即可访问 Apache 包。

编辑:忘记链接;)

于 2008-08-28T01:31:53.187 回答
1

虽然不是 vanilla-Java,但我将提供一个更简单的解决方案。使用 Groovy ;-)

String siteContent = new URL("http://www.google.com").text
于 2013-03-05T09:16:53.393 回答
-3

它不是库,而是一个名为 curl 的工具,通常安装在大多数服务器中,或者您可以通过以下方式轻松安装在 ubuntu 中

sudo apt install curl

然后获取任何 html 页面并将其存储到您的本地文件中,例如示例

curl https://www.facebook.com/ > fb.html

您将获得主页 html。您也可以在浏览器中运行它。

于 2018-07-14T10:57:56.147 回答