【发布时间】:2010-09-07 02:01:04
【问题描述】:
在不使用任何外部库的情况下,将网站的 HTML 内容提取到字符串中的最简单方法是什么?
【问题讨论】:
标签: java html screen-scraping
在不使用任何外部库的情况下,将网站的 HTML 内容提取到字符串中的最简单方法是什么?
【问题讨论】:
标签: java html screen-scraping
我目前正在使用这个:
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);
但不确定是否有更好的方法。
【讨论】:
我刚刚离开this post in your other thread,尽管您上面的内容可能也可以。我认为任何一个都不会比另一个更容易。只需在代码顶部使用 import org.apache.commons.HttpClient 即可访问 Apache 包。
编辑:忘记链接;)
【讨论】:
这对我来说效果很好:
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);
}
不确定提供的其他解决方案是否更有效。
【讨论】:
while之后,你也应该显示缓冲区的内容!或者写一个你读过的方法!
close输入流
虽然不是 vanilla-Java,但我会提供一个更简单的解决方案。使用 Groovy ;-)
String siteContent = new URL("http://www.google.com").text
【讨论】:
它不是库,而是一个名为 curl 的工具,通常安装在大多数服务器中,或者您可以通过 ubuntu 轻松安装
sudo apt install curl
然后获取任何 html 页面并将其存储到您的本地文件中,例如示例
curl https://www.facebook.com/ > fb.html
您将获得主页 html。您也可以在浏览器中运行它。
【讨论】: