如何以编程方式下载Java中的网页

我希望能够获取一个网页的HTML并将其保存到一个String ,所以我可以做一些处理。 另外,我怎样才能处理各种类型的压缩。

我将如何去做这个使用Java?

以下是使用Java的URL类的一些测试代码。 尽管如此,我建议比我在这里处理异常或将它们传递给调用堆栈的工作做得更好。

 public static void main(String[] args) { URL url; InputStream is = null; BufferedReader br; String line; try { url = new URL("http://stackoverflow.com/"); is = url.openStream(); // throws an IOException br = new BufferedReader(new InputStreamReader(is)); while ((line = br.readLine()) != null) { System.out.println(line); } } catch (MalformedURLException mue) { mue.printStackTrace(); } catch (IOException ioe) { ioe.printStackTrace(); } finally { try { if (is != null) is.close(); } catch (IOException ioe) { // nothing to see here } } } 

我会用像Jsoup一样体面的HTML解析器。 这就像:

 String html = Jsoup.connect("http://stackoverflow.com").get().html(); 

它完全透明地处理GZIP和分块响应和字符编码。 它也提供了更多的优势,比如HTML 遍历和CSS选择器的操作 ,就像jQuery所能做的那样。 你只需要抓取它作为Document ,而不是一个String

 Document document = Jsoup.connect("http://google.com").get(); 

你真的不想运行基本的字符串方法,甚至不想运行HTML来处理它。

也可以看看:

  • Java中领先的HTML解析器有什么优点和缺点?

比尔的答案非常好,但是你可能想要做一些压缩或用户代理的请求。 以下代码显示了如何对您的请求进行各种类型的压缩。

 URL url = new URL(urlStr); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); // Cast shouldn't fail HttpURLConnection.setFollowRedirects(true); // allow both GZip and Deflate (ZLib) encodings conn.setRequestProperty("Accept-Encoding", "gzip, deflate"); String encoding = conn.getContentEncoding(); InputStream inStr = null; // create the appropriate stream wrapper based on // the encoding type if (encoding != null && encoding.equalsIgnoreCase("gzip")) { inStr = new GZIPInputStream(conn.getInputStream()); } else if (encoding != null && encoding.equalsIgnoreCase("deflate")) { inStr = new InflaterInputStream(conn.getInputStream(), new Inflater(true)); } else { inStr = conn.getInputStream(); } 

还要设置用户代理添加以下代码:

 conn.setRequestProperty ( "User-agent", "my agent name"); 

那么你可以使用URL和URLConnection这样的内置库,但是它们不能给予太多的控制。

就我个人而言,我会去Apache的HTTPClient库。
编辑: HTTPClient已被设置为由Apache 生命尽头 。 替换是: HTTP组件

上述所有方法都不会像浏览器中那样下载网页文本。 现在很多数据都通过html页面中的脚本加载到浏览器中。 上述技术都不支持脚本,只是下载html文本。 HTMLUNIT支持javascripts。 所以如果你正在寻找下载浏览器中的网页文本,那么你应该使用HTMLUNIT 。

在Unix / Linux上,你可以运行'wget',但是如果你正在编写一个跨平台的客户端,这不是一个真正的选择。 当然,这个假定你并不是真的想要从下载的数据到下载的数据之间做很多的事情。

尝试使用jsoup库。

 import java.io.IOException; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; public class ParseHTML { public static void main(String args[]) throws IOException{ Document doc = Jsoup.connect("https://www.wikipedia.org/").get(); String text = doc.body().text(); System.out.print(text); } } 

你可以在这里下载jsoup库。

这对我有效

 package test; import java.net.*; import java.io.*; public class PDFTest { public static void main(String[] args) throws Exception { try { URL oracle = new URL("http://www.fetagracollege.org"); BufferedReader in = new BufferedReader(new InputStreamReader(oracle.openStream())); String fileName = "D:\\a_01\\output.txt"; PrintWriter writer = new PrintWriter(fileName, "UTF-8"); OutputStream outputStream = new FileOutputStream(fileName); String inputLine; while ((inputLine = in.readLine()) != null) { System.out.println(inputLine); writer.println(inputLine); } in.close(); } catch(Exception e) { } } } 

Jetty有一个可以用来下载网页的HTTP客户端。

 package com.zetcode; import org.eclipse.jetty.client.HttpClient; import org.eclipse.jetty.client.api.ContentResponse; public class ReadWebPageEx5 { public static void main(String[] args) throws Exception { HttpClient client = null; try { client = new HttpClient(); client.start(); String url = "http://www.something.com"; ContentResponse res = client.GET(url); System.out.println(res.getContentAsString()); } finally { if (client != null) { client.stop(); } } } } 

该示例打印一个简单的网页的内容。

在阅读Java教程的网页中,我写了六个使用URL,JSoup,HtmlCleaner,Apache HttpClient,Jetty HttpClient和HtmlUnit以Java语言下载程序的例子。