gpt4 book ai didi

java - jsoup - 如何从维基百科文章的文本中获取链接

转载 作者:行者123 更新时间:2023-11-30 06:30:28 26 4
gpt4 key购买 nike

我刚刚开始探索 Jsoup 并遇到了以下问题:当我尝试从 https://en.wikipedia.org/wiki/Knowledge 提取仅属于英文版维基百科一切正常。

    Document document = Jsoup.connect("https://en.wikipedia.org/wiki/Knowledge").timeout(6000).get();
Elements linksOnPage = document.select( "a[href^=\"/wiki/\"]");

for (Element link : linksOnPage) {
System.out.println("link : " + link.attr("abs:href"));
}
}

但是我也收到了不属于当前文章文本的链接,例如:

    link : https://en.wikipedia.org/wiki/Main_Page
link : https://en.wikipedia.org/wiki/Portal:Contents
link : https://en.wikipedia.org/wiki/Portal:Featured_content
link : https://en.wikipedia.org/wiki/Portal:Current_events
link : https://en.wikipedia.org/wiki/Special:Random
link : https://en.wikipedia.org/wiki/Help:Contents
link : https://en.wikipedia.org/wiki/Wikipedia:About
link : https://en.wikipedia.org/wiki/Wikipedia:Community_portal

使用 Jsoup 仅获取指向其他维基百科文章的文本的链接的正确方法是什么?

最佳答案

links that I do not need are located in the div id="mw-panel"

因此正确的选择器是:

div:not(#mw-panel) a[href^="/wiki/"]

这将选择 <a>元素:

  • 不在 <div> 内元素为 mw-panel身份证号
  • 和他们的href属性以 "/wiki/" 开头.

编辑:

I need only the links from an article without links from the side panels and without any links such as https://en.wikipedia.org/wiki/Special:BookSources/978-1-4200‌​-5940-3 https://en.wikipedia.org/wiki/Special:BookSources/1-58450-46‌​0-9

那么你可以尝试:

#bodyContent a[href^="/wiki/"]

这将解析以下链接:

  • 位于文章内(<div>,ID 为 bodyContent)
  • 他们的href属性以 "/wiki/" 开头

div#bodyContent没有"/wiki/...Special:..."链接。 (如果您想排除带有其他单词的链接,请将其附加到上述选择器的末尾,不带任何空格或分隔符: :not([href*="something"]) )

您还可以根据我上面的尝试和 reading about Jsoup selectors 尝试组合选择器以实现最佳模式。 .

示例代码:

String url = "https://en.wikipedia.org/wiki/Knowledge";
Document document = Jsoup.connect(url).timeout(6000).get();
Elements links = document.select("#bodyContent a[href^=\"/wiki/\"]");
for (Element e : links) {
System.out.println(e.attr("href"));
}
System.out.println("Links found: " + links.size());

这会打印出以下内容:

/wiki/Knowledge_(disambiguation)
/wiki/Fact
/wiki/Information
...
/wiki/Category:Articles_with_unsourced_statements_from_September_2007
/wiki/Category:Articles_with_unsourced_statements_from_May_2009
/wiki/Category:Wikipedia_articles_with_GND_identifiers
Links found: 826

关于java - jsoup - 如何从维基百科文章的文本中获取链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46257841/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com