【问题标题】:JSOUP get the html content from redirected linkJSOUP 从重定向链接获取 html 内容
【发布时间】:2016-03-23 20:14:04
【问题描述】:

考虑以下网址http://www.google.com/url?rct=j&sa=t&url=http://www.ksat.com/news/father-of-woman-killed-in-memorial-day-floods-testifies-for-better-flood-warnings&ct=ga&cd=CAIyHWU3NmVhMGQ0NWQ3MmRmY2I6Y29tOmVuOlVTOlJM&usg=AFQjCNE_8XwECqkmyPIMzcSxCDh2hP16wQ。当我将此url 传递给JSOUP 时,html 内容不准确。但是当我在浏览器中打开这个网址时,它会重定向到http://www.ksat.com/news/father-of-woman-killed-in-memorial-day-floods-testifies-for-better-flood-warnings。

然后,我将这个url 传递给jsoup,现在我得到了准确的html 内容。

如何从第一个 url 中获取准确的 html 内容??

我尝试了很多选择

        Response response = Jsoup.connect(url).followRedirects(true).timeout(timeOut*1000).userAgent(userAgent).execute();
        int status = response.statusCode();
        if (status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_MOVED_PERM || status == HttpURLConnection.HTTP_SEE_OTHER) {
            redirectUrl = response.header("location");
            response = Jsoup.connect(redirectUrl).followRedirects(false).timeout(timeOut*1000).userAgent(userAgent).execute();
        }
        Document doc=response.parse();

我尝试了很多user agents、.referrer("http://google.com") 选项等。 我目前使用的是jsoup 1.8.3 版。

【问题讨论】:

    标签: java url html-parsing jsoup


    【解决方案1】:

    Google 返回一个带有 JavaScript/META 重定向的 html 页面:

    <script>window.googleJavaScriptRedirect=1</script><script>var n={navigateTo:function(b,a,d){if(b!=a&&b.google){if(b.google.r){b.google.r=0;b.location.href=d;a.location.replace("about:blank");}}else{a.location.replace(d);}}};n.navigateTo(window.parent,window,"http://www.ksat.com/news/father-of-woman-killed-in-memorial-day-floods-testifies-for-better-flood-warnings");
    </script><noscript><META http-equiv="refresh" content="0;URL='http://www.ksat.com/news/father-of-woman-killed-in-memorial-day-floods-testifies-for-better-flood-warnings'"></noscript>
    

    这与 HTTP 重定向标头不同,因为 Jsoup 不解释 JavaScript,所以你不走运。

    但是,您当然可以对其进行解析以获取真正的链接。这当然可以在不访问 Google 的情况下实现,因为链接是原始 URL 中参数的一部分。

    【讨论】:

    猜你喜欢
    • 2022-01-02
    • 1970-01-01
    • 2017-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多