2017-09-12 12 views
0
import java.io.IOException; 

import org.jsoup.Jsoup; 
import org.jsoup.nodes.Document; 
import org.jsoup.nodes.Element; 


public class Main { 
    public static void main(String[] args) throws Exception { 
     Document d=Jsoup.connect("https://osu.ppy.sh/u/charless").get(); 

     for(Element line : d.select("div.profileStatLine")) { 
      System.out.println(d.select("b").text()); 
     } 
    } 
} 

div.profileStatLineのテキスト「2027pp​​(#97,094)」の取得に問題があります。これは出力すべきですが、出力しません。 URL:https://osu.ppy.sh/u/charlessJSoup:要素からのテキストの取得に関する問題

+1

問題は何ですか? – Reimeus

+0

何も出力せず、質問に追加しました。 –

+0

[ページコンテンツがjavascriptで読み込まれ、Jsoupには表示されません](https://stackoverflow.com/questions/7488872/page-content-is-loaded-with-javascript-and-jsoup-doesnt- see-it) – teppic

答えて

1

ページの一部にjavascriptが読み込まれているため、探しているdivが表示されません。

ブラウザを使用して、ページを読み込み、解析する前にJavaScriptを解釈することができます。 webdrivermanagerのような図書館が役に立ちます。

public static void main(String[] args) throws Exception { 
    ChromeDriverManager.getInstance().setup(); 
    ChromeDriver chromeDriver = new ChromeDriver(); 
    chromeDriver.get("https://osu.ppy.sh/u/charless"); 

    Document d = Jsoup.parse(chromeDriver.getPageSource()); 

    chromeDriver.close(); 

    for (Element line : d.select("div.profileStatLine")) { 
     System.out.println(line.select("b").text()); 
    } 
} 

代わりに、ページ内のjavascriptを調べて、データを取得するのと同じ呼び出しを行うこともできます。

ページはhttps://osu.ppy.sh/pages/include/profile-general.php?u=4084042&m=0からプロファイルをロードしています。 uは単純にユーザーIDであり、ページから比較的簡単に抽出できます。

public class ProfileScraper { 
    private static final Pattern UID_PATTERN = Pattern.compile("var userId = (\\d+);"); 

    public static void main(String[] args) throws IOException { 
     String uid = getUid("charless"); 
     Document d = Jsoup.connect("https://osu.ppy.sh/pages/include/profile-general.php?u=" + uid).get(); 

     for (Element line : d.select("div.profileStatLine")) { 
      System.out.println(line.select("b").text()); 
     } 
    } 

    public static String getUid(String name) throws IOException { 
     Document d1 = Jsoup.connect("https://osu.ppy.sh/u/" + name).get(); 

     for (Element script : d1.select("script")) { 
      String text = script.data(); 
      Matcher uidMatcher = UID_PATTERN.matcher(text); 
      if (uidMatcher.find()) { 
       return uidMatcher.group(1); 
      } 
     } 
     throw new IOException("No such character"); 
    } 
} 
+0

私は走ったので、これはうまくいった。ただ問題は、私が作っているプログラムが最終的にサーバーに置かれるボットだからです。だから、この方法がその環境でも動作するかどうかは疑問です。 –

+0

セレンは何の問題もなくヘッドレスで走りますが、あなたがしていることに対してかなり重いでしょう。あなたのもう1つの選択肢は、ページをリバースエンジニアリングして、あなたが行っているコンテンツをロードするためにjavascriptが何をしているのかを発見することです。 – teppic

+0

代替案を追加するための答えを編集しました。 – teppic

関連する問題