120

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

我将如何使用 Java 来做到这一点?

4

11 回答 11

179

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

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

它完全透明地处理 GZIP 和分块响应以及字符编码。它还提供了更多的优势,比如像 jQuery 一样通过 CSS 选择器进行HTML遍历操作。你只需要把它当作Document,而不是String

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

您真的不想在 HTML 上运行基本的 String 方法甚至是正则表达式来处理它。

也可以看看:

于 2010-12-31T17:57:30.997 回答
113

下面是一些使用 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
        }
    }
}
于 2008-10-26T21:09:39.497 回答
27

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

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");
于 2010-04-06T05:17:00.170 回答
13

好吧,您可以使用URLURLConnection等内置库,但它们并没有提供太多控制。

我个人会选择Apache HTTPClient库。
编辑: HTTPClient 已被Apache设置为生命周期结束。替换为:HTTP 组件

于 2008-10-26T20:20:45.307 回答
9

上述所有方法都不会像在浏览器中那样下载网页文本。如今,大量数据通过 html 页面中的脚本加载到浏览器中。上述技术均不支持脚本,它们仅下载 html 文本。HTMLUNIT 支持 javascripts。因此,如果您希望下载浏览器中的网页文本,那么您应该使用HTMLUNIT

于 2014-05-30T10:30:16.080 回答
2

您很可能需要从安全网页(https 协议)中提取代码。在以下示例中,html 文件被保存到 c:\temp\filename.html 享受!

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;

import javax.net.ssl.HttpsURLConnection;

/**
 * <b>Get the Html source from the secure url </b>
 */
public class HttpsClientUtil {
    public static void main(String[] args) throws Exception {
        String httpsURL = "https://stackoverflow.com";
        String FILENAME = "c:\\temp\\filename.html";
        BufferedWriter bw = new BufferedWriter(new FileWriter(FILENAME));
        URL myurl = new URL(httpsURL);
        HttpsURLConnection con = (HttpsURLConnection) myurl.openConnection();
        con.setRequestProperty ( "User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:63.0) Gecko/20100101 Firefox/63.0" );
        InputStream ins = con.getInputStream();
        InputStreamReader isr = new InputStreamReader(ins, "Windows-1252");
        BufferedReader in = new BufferedReader(isr);
        String inputLine;

        // Write each line into the file
        while ((inputLine = in.readLine()) != null) {
            System.out.println(inputLine);
            bw.write(inputLine);
        }
        in.close(); 
        bw.close();
    }
}
于 2018-10-27T17:55:52.063 回答
1

为此,使用 NIO.2 强大的 Files.copy(InputStream in, Path target):

URL url = new URL( "http://download.me/" );
Files.copy( url.openStream(), Paths.get("downloaded.html" ) );
于 2020-06-15T19:23:00.267 回答
0

在 Unix/Linux 机器上,您可以只运行“wget”,但如果您正在编写跨平台客户端,这不是一个真正的选择。当然,这假设您真的不想对下载的数据在下载到磁盘之间进行太多操作。

于 2008-10-26T20:43:45.667 回答
0

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://example.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 中下载网页的示例。

于 2016-08-18T16:42:58.213 回答
0

从这个类中获得帮助,它会获取代码并过滤一些信息。

public class MainActivity extends AppCompatActivity {

    EditText url;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate( savedInstanceState );
        setContentView( R.layout.activity_main );

        url = ((EditText)findViewById( R.id.editText));
        DownloadCode obj = new DownloadCode();

        try {
            String des=" ";

            String tag1= "<div class=\"description\">";
            String l = obj.execute( "http://www.nu.edu.pk/Campus/Chiniot-Faisalabad/Faculty" ).get();

            url.setText( l );
            url.setText( " " );

            String[] t1 = l.split(tag1);
            String[] t2 = t1[0].split( "</div>" );
            url.setText( t2[0] );

        }
        catch (Exception e)
        {
            Toast.makeText( this,e.toString(),Toast.LENGTH_SHORT ).show();
        }

    }
                                        // input, extrafunctionrunparallel, output
    class DownloadCode extends AsyncTask<String,Void,String>
    {
        @Override
        protected String doInBackground(String... WebAddress) // string of webAddress separate by ','
        {
            String htmlcontent = " ";
            try {
                URL url = new URL( WebAddress[0] );
                HttpURLConnection c = (HttpURLConnection) url.openConnection();
                c.connect();
                InputStream input = c.getInputStream();
                int data;
                InputStreamReader reader = new InputStreamReader( input );

                data = reader.read();

                while (data != -1)
                {
                    char content = (char) data;
                    htmlcontent+=content;
                    data = reader.read();
                }
            }
            catch (Exception e)
            {
                Log.i("Status : ",e.toString());
            }
            return htmlcontent;
        }
    }
}
于 2017-12-16T17:23:19.400 回答
-1

我使用了这篇文章的实际答案(url)并将输出写入文件。

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) {

        }

    }
}
于 2017-10-26T08:42:30.323 回答