如何在Java中获取HTML

pek*_*pek 26 html java screen-scraping

如果不使用任何外部库,将网站的HTML内容提取到String中的最简单方法是什么?

pek*_*pek 35

我目前正在使用这个:

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);
Run Code Online (Sandbox Code Playgroud)

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

  • 为什么"\\ Z"?它不仅仅是Windows上的EOF吗?我只想猜到这里. (5认同)
  • 为什么用“\\Z”?它有什么作用?我尝试没有它,但没有成功。 (2认同)

Sco*_*ish 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);
}
Run Code Online (Sandbox Code Playgroud)

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

  • 当然可以,但它们是核心 java,所以非常简单。至于实际代码,为了清楚起见,省略了导入语句。 (2认同)
  • 确保“关闭”输入流 (2认同)