鍍金池/ 問答/Java  HTML/ Java 獲取用 URL 獲取 HTML 頁面源碼出錯

Java 獲取用 URL 獲取 HTML 頁面源碼出錯

我想獲取指定URL的頁面源碼,代碼如下:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;

public class Test {
    public static void main(String[] args) {
        URL url;
        InputStream is = null;
        BufferedReader br;
        String line = null;
        String urlStr = "https://weibo.com/tv/v/G0Eg72F68";
        try {
            url = new URL(urlStr);
            is = url.openStream();  // throws an IOException
            br = new BufferedReader(new InputStreamReader(is));

            while ((line = br.readLine()) != null) {
                    //if (line.contains("video-sources")) {
                        System.out.println(line);
                    //    break;
                    //}
                
            }
            System.out.println("this is the end");
        } catch (MalformedURLException mue) {
             mue.printStackTrace();
        } catch (IOException ioe) {
             ioe.printStackTrace();
        } finally {
            try {
                if (is != null) is.close();
            } catch (IOException ioe) {
                // nothing to see here
            }
        }
    }
    
}

但是返回的字符串跟頁面實際的源碼不一樣,差距很大,請問這是怎么回事?有什么解決辦法?
非常感謝!
P.S. 不是亂碼的問題,是返回的源碼內容跟本來頁面的內容差距很大。原頁面的源碼中有很多dom元素,而返回的源碼基本就只有一些js代碼。感覺返回的并不是我想要的頁面的源碼。

回答
編輯回答
萌吟

InputStreamReader 默認會使用當前環(huán)境的編碼進行數(shù)據(jù)讀取,你提供的網(wǎng)頁是GB2312編碼,你應該在UTF8編碼下執(zhí)行所以會出現(xiàn)亂碼:
可以試試:

br = new BufferedReader(new InputStreamReader(is, "GB2312"));

指定InputStreamReader使用的編碼;

  1. 建議你可以多看看Java中的編碼相關的東西;
  2. 如果你是要做數(shù)據(jù)爬蟲,其實也有很多很優(yōu)秀的第三方框架可以嘗試,jsoup/httpclient等。
2018年7月8日 12:36