从维基数据页面抓取链接

Scrape links from wikidata page

<table class="sparql" border="1">
  <tbody><tr>
    <th>simpleProperty</th>
  </tr>
  <tr>
    <td><a href="http://www.wikidata.org/entity/P115c">http://www.wikidata.org/entity/P115c</a></td>
  </tr>
</tbody></table>

使用 Jsoup,我试图从看起来像 this.

的页面中收集所有 links

我一直在尝试许多不同的方法,但我似乎无法确定。最近我试过这样:

// parse the input stream using Jsoup
docx = Jsoup.parse(wiki_relation_InputStream, null, wikidata_relation_page.getProtocol()+"://"+wikidata_relation_page.getHost()+"/");

Element table = doc.select("table").first(); //gets a table with the class "first class"
Elements links = table.select("a[href]");

看起来应该很容易,因为结构是如此之小,但是,唉,还是给我带来了一些麻烦。

如果不止一个我想全部收集起来。在零的情况下,如果程序没有在死亡和破坏的火球中崩溃,我更愿意。

如何获得难以捉摸的 link 文本? (例如 http://www.wikidata.org/entity/P115c

更新

根据熊猫的建议

//get it's normal wiki disambig page
String URL_czech = "http://milenio.dcc.uchile.cl/sparql?default-graph-uri=&query=PREFIX+%3A+%3Chttp%3A%2F%2Fwww.wikidata.org%2Fentity%2F%3E%0D%0ASELECT+*+WHERE+%7B%0D%0A+++%3A" 
        + home + "+%3FsimpleProperty+%3A" 
        + away + "%0D%0A%7D%0D%0A&format=text%2Fhtml&timeout=0&debug=on";

URL wikidata_page = new URL(URL_czech);
HttpURLConnection wiki_connection = (HttpURLConnection)wikidata_page.openConnection();
InputStream wikiInputStream = null;


try 
{
    // try to connect and use the input stream
    wiki_connection.connect();
    wikiInputStream = wiki_connection.getInputStream();
} 
catch(IOException error) 
{
    // failed, try using the error stream
    wikiInputStream = wiki_connection.getErrorStream();
}
    // parse the input stream using Jsoup
    Document docx = Jsoup.parse(wikiInputStream, null, wikidata_page.getProtocol()+"://"+wikidata_page.getHost()+"/");



Elements link_text = docx.select("table.sparql > tbody > tr:nth-child(2) > td > a");
//link_text.text();
for (Element l : link_text) 
{
    String output = l.text();
    System.out.println( output );
}

下面的东西可以得到 table 但如何进一步向下钻取:

Elements tables = docx.select("table.sparql");

for(Element table : tables)
{
     System.out.println(table.toString());
}

这样可以吗?

List<String> links = new ArrayList<>();
for(Element a : doc.select("table.sparql tr td a")) {
   String href = a.attr("href");
   String linkText = a.text();
   links.add(href);
}

我在 http://try.jsoup.org/ 上尝试了以下 CSS 选择器查询,它似乎让我得到文本 http://www.wikidata.org/entity/P26c:

table.sparql > tbody > tr:nth-child(2)

试试这个代码:

Element link_text = document.select("table.sparql > tbody > tr:nth-child(2)");
link_text.getText(); //or I think its text() method

这似乎也能正常工作:

table.sparql > tbody > tr:nth-child(2) > td > a