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代码。感觉返回的并不是我想要的页面的源码。

阅读 1.8k
1 个回答

InputStreamReader 默认会使用当前环境的编码进行数据读取,你提供的网页是GB2312编码,你应该在UTF8编码下执行所以会出现乱码:
可以试试:

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

指定InputStreamReader使用的编码;

  1. 建议你可以多看看Java中的编码相关的东西;
  2. 如果你是要做数据爬虫,其实也有很多很优秀的第三方框架可以尝试,jsoup/httpclient等。
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题