質問

jsoupの使用に問題があります。私がやろうとしているのは、機能しないメタ更新URLに基​​づいて別のURLにリダイレクトされるURLからドキュメントを取得することです。という名前のWebサイトURLを入力しているかどうかを明確に説明するために http://www.amerisourcebergendrug.com 自動的にリダイレクトされます http://www.amerisourcebergendrug.com/abcdrug/ メタ更新URLに応じて異なりますが、私のjsoupはまだ残っています http://www.amerisourcebergendrug.com リダイレクトやフェッチは行わない http://www.amerisourcebergendrug.com/abcdrug/

Document doc = Jsoup.connect("http://www.amerisourcebergendrug.com").get();

私も使ってみましたが、

Document doc = Jsoup.connect("http://www.amerisourcebergendrug.com").followRedirects(true).get();

しかし両方とも機能していません

これに対する回避策はありますか?

アップデート:ページではメタ更新リダイレクト メソッドが使用される場合があります

役に立ちましたか?

解決

更新 (大文字と小文字を区別せず、かなりのフォールト トレラント)


public static void main(String[] args) throws Exception {

    URI uri = URI.create("http://www.amerisourcebergendrug.com");

    Document d = Jsoup.connect(uri.toString()).get();

    for (Element refresh : d.select("html head meta[http-equiv=refresh]")) {

        Matcher m = Pattern.compile("(?si)\\d+;\\s*url=(.+)|\\d+")
                           .matcher(refresh.attr("content"));

        // find the first one that is valid
        if (m.matches()) {
            if (m.group(1) != null)
                d = Jsoup.connect(uri.resolve(m.group(1)).toString()).get();
            break;
        }
    }
}

正しく出力されます:

http://www.amerisourcebergendrug.com/abcdrug/

古い答え:

機能していないと確信していますか。私にとって:

System.out.println(Jsoup.connect("http://www.ibm.com").get().baseUri());

..出力 http://www.ibm.com/us/en/ 正しく..

他のヒント

エラー処理と大文字小文字の区別の問題を改善するため

try
{
    Document doc = Jsoup.connect("http://www.ibm.com").get();
    Elements meta = doc.select("html head meta");
    if (meta != null)
    {
        String lvHttpEquiv = meta.attr("http-equiv");
        if (lvHttpEquiv != null && lvHttpEquiv.toLowerCase().contains("refresh"))
        {
            String lvContent = meta.attr("content");
            if (lvContent != null)
            {
                String[] lvContentArray = lvContent.split("=");
                if (lvContentArray.length > 1)
                    doc = Jsoup.connect(lvContentArray[1]).get();
            }
        }
    }

    // get page title
    return doc.title();

}
catch (IOException e)
{
    e.printStackTrace();
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top