<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,我试图从看起来像这的页面中收集所有的链接。
我尝试了很多不同的方法,但我似乎无法确定。最近我试过这样做:
// 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]");它看起来应该很容易,因为它的结构是如此的小,但遗憾的是,它给我带来了一些麻烦。
在不止一个的情况下,我想把它们全部收集起来。在没有零的情况下,我更希望这个程序不会在死亡和毁灭的火球中崩溃。
如何得到那个难以捉摸的链接文本?(例如在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 );
}下面的东西可以得到表,但是如何钻得更深:
Elements tables = docx.select("table.sparql");
for(Element table : tables)
{
System.out.println(table.toString());
}发布于 2015-04-28 11:45:53
我在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
发布于 2015-04-28 11:07:43
这个能胜任工作吗?
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);
}https://stackoverflow.com/questions/29917548
复制相似问题