jsoup文档在整个链接中不可见

时间:2015-07-28 11:11:31

标签: jsoup

我将一个URL(https://es.wikipedia.org/wiki/Abjasia)解析为jsoup.Document,但是当我要获取一个链接的URL(其他语言的同一页面)时,我发现href不是完全完成了。

当我直接从网上看到源代码时,我可以看到:

<li><a href="//en.wikipedia.org/wiki/Abkhazia" title="Abkhazia (inglés)" lang="en" hreflang="en">English</a></li>

,而在文件上我有:

<li class="interlanguage-link interwiki-en"><a href="//en.wikipedia.org/wiki/" title="inglés" lang="en" hreflang="en">English</a></li>

我正在尝试不同的编码,但我认为没有关系。

使用的代码是:

URL pageUrl = new URL(url);
URLConnection urlConnection = pageUrl.openConnection();
InputStream is = urlConnection.getInputStream();
InputStreamReader isr = new InputStreamReader(is, "UTF-8");
Document doc = Jsoup.parse(sb.toString(), "UTF-8");
Element countryTable = doc.getElementById("mw-panel");
Element languages = countryTable.getElementsByClass("portal").get(3);
Element listLanguages = languages.select("div").get(0);
Elements countryList = listLanguages.select("ul").select("li");
String a = countryList.get(0).select("a").toString();

有一些解释吗? 非常感谢

2 个答案:

答案 0 :(得分:0)

我不确定你为什么使用urlConnection = pageUrl.openConnection();但是,在你的代码示例中,你凭空产生字符串缓冲区sb(我猜它是一个字符串缓冲区?)。我的编译器不愿意编译它。我改变了你的代码,这似乎对我有用(使用Apache IOUtils):

URL pageUrl = new URL("https://es.wikipedia.org/wiki/Abjasia");
URLConnection urlConnection = pageUrl.openConnection();
InputStream is = urlConnection.getInputStream();
InputStreamReader isr = new InputStreamReader(is, "UTF-8");
String theString = IOUtils.toString(isr); 

Document doc = Jsoup.parse(theString, "https://es.wikipedia.org/");
Element countryTable = doc.getElementById("mw-panel");
Element languages = countryTable.getElementsByClass("portal").get(3);
Element listLanguages = languages.select("div").get(0);
Elements countryList = listLanguages.select("ul").select("li");
String a = countryList.get(0).select("a").toString();

注意,Jsoup.parse()将BASE URi作为第二个参数,而不是编码。

我会使用这个版本:

Document doc = Jsoup
   .connect("https://es.wikipedia.org/wiki/Abjasia")
   .get();
Elements countryAs = doc.select("#mw-panel li.interlanguage-link>a");
String firstAStr = countryAs.get(0).text();

答案 1 :(得分:0)

你说的方式,luksch,为我工作!! 使用

this.BeginInvoke

没有必要使用Streams,也不需要打开URL。

谢谢!