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

jjn*_*guy 116 java compression http

我希望能够获取一个网页的html并将其保存到一个String,所以我可以对它进行一些处理.另外,我如何处理各种类型的压缩.

我将如何使用Java进行此操作?

Bal*_*usC 169

我会使用像Jsoup这样体面的HTML解析器.然后就像这样简单:

String html = Jsoup.connect("http://stackoverflow.com").get().html();
Run Code Online (Sandbox Code Playgroud)

它完全透明地处理GZIP和分块响应以及字符编码.它提供了更多的优势,例如像CSS查询器的HTML 遍历操作,就像jQuery可以做的那样.你只需抓住它Document,而不是像String.

Document document = Jsoup.connect("http://google.com").get();
Run Code Online (Sandbox Code Playgroud)

你真的希望运行的基本字符串的方法,甚至正则表达式的HTML来处理它.

也可以看看:

  • 总比没有好. (55认同)
  • 好答案.有一点晚.`)` (3认同)

Bil*_*ard 107

这是使用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
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 不推荐使用DataInputStream.readLine(),但除了非常好的示例之外.我使用包装在BufferedReader()中的InputStreamReader()来获取readLine()函数. (16认同)
  • 这不会考虑字符编码,因此虽然它似乎适用于ASCII文本,但是当它不匹配时最终会导致"奇怪的字符". (2认同)
  • 关闭`InputStreamReader`怎么样? (2认同)

jjn*_*guy 24

Bill的答案非常好,但您可能希望对压缩或用户代理等请求做一些事情.以下代码显示了如何对请求进行各种类型的压缩.

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

要同时设置user-agent,请添加以下代码:

conn.setRequestProperty ( "User-agent", "my agent name");
Run Code Online (Sandbox Code Playgroud)


Jon*_*eet 12

好吧,你可以使用内置库,如URLURLConnection,但它们不会给予很多控制.

我个人会选择Apache HTTPClient库.
编辑: Apache已将HTTPClient设置为报废.替换是:HTTP组件


小智 7

所有上述方法都不会下载浏览器中显示的网页文本.这些天,很多数据都是通过html页面中的脚本加载到浏览器中的.上述技术都不支持脚本,它们只是下载html文本.HTMLUNIT支持javascripts.因此,如果您要在浏览器中查找网页文本,那么您应该使用HTMLUNIT.