【问题标题】:reading web page source code in java Differs from the orginal webpage source code在java中读取网页源代码与原始网页源代码不同
【发布时间】:2017-06-04 00:30:56
【问题描述】:

我正在尝试实现程序来读取网页源代码并将其保存在文本文件中,然后在其中执行一些操作,但是当我读取网页源代码时出现问题,原始网页源代码和输出之间存在差异java程序网页源代码。

我的程序:

        String inputLine;
        URL link = new URL("http://www.ammanu.edu.jo/English/Articles/newsArticle.aspx?id=2935");
        BufferedReader in = new BufferedReader( new InputStreamReader(link.openStream(),"UTF-8"));

        while ((inputLine = in.readLine()) != null){
                System.out.println(inputLine);
        }
        in.close();

以及我在这行源代码中的问题

第 1156 行的原始网页源代码:

<img id="img" src="http://www.ammanu.edu.jo/AdminImages/20652935/_DSC0246.jpg" style="height:310px;width:400px;border-width:0px;display:block;float:left; padding-right:5px;" />

java程序的实际输出:

<img id="img" src="http://www.ammanu.edu.jo/AdminImages/20652935/_DSC0246.jpg" height="310" width="400" border="0" style="display:block;float:left; padding-right:5px;" />

对于这个问题有什么建议的解决方案吗?

【问题讨论】:

    标签: java webpage html-content-extraction web-content


    【解决方案1】:

    您必须将用户设置为用户代理:

    con.setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.4; en-US; rv:1.9.2.2) Gecko/20100316 Firefox/3.6.2");
    

    完整代码:

        String inputLine;
        URL link = new URL("http://www.ammanu.edu.jo/English/Articles/newsArticle.aspx?id=2935");
        URLConnection con = link.openConnection();
        con.setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.4; en-US; rv:1.9.2.2) Gecko/20100316 Firefox/3.6.2");
    
        BufferedReader in = new BufferedReader( new InputStreamReader(con.getInputStream(),"UTF-8"));
    
        while ((inputLine = in.readLine()) != null){
            System.out.println(inputLine);
        }
        in.close();
    

    结果

    <img id="img" src="http://www.ammanu.edu.jo/AdminImages/20652935/_DSC0246.jpg" style="height:310px;width:400px;border-width:0px;display:block;float:left; padding-right:5px;" />
    

    【讨论】:

    • 谢谢,你能解释一下con.setRequestProperty的目的吗
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-13
    • 1970-01-01
    • 1970-01-01
    • 2011-11-30
    相关资源
    最近更新 更多