【问题标题】:JSoup XPath/Selector query not workingJSoup XPath/Selector 查询不起作用
【发布时间】:2018-06-01 11:08:27
【问题描述】:

我正在尝试从此页面中提取 GitHub 链接

https://plugins.jenkins.io/hugo

val doc = JSoup.parse("https://plugins.jenkins.io/hugo")

来自 Chrome 的 XPath

//*[@id="grid-box"]/div/section/div[2]/div[2]/div/div/div[1]/div/div/div[1]/div[2]/a

Chrome 中的选择器

#grid-box > div > section > div.dialog > div.content > div > div > div.col-md-9.main > div > div > div:nth-child(1) > div:nth-child(2) > a

JSoup 查询

#grid-box > div > section > div:eq(2) > div:eq(2) > div > div > div:eq(1) > div > div > div:eq(1) > div:eq(2) > a

代码片段

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import us.codecraft.xsoup.Xsoup;

val doc = Jsoup.parse("https://plugins.jenkins.io/hugo")
Xsoup.compile("""//*[@id="grid-box"]/div/section/div[2]/div[2]/div/div/div[1]/div/div/div[1]/div[2]/a""").evaluate(doc).list

也尝试过 XPath、Selector,但无法提取值

我需要这个页面上的 github 链接

<a href="https://github.com/jenkinsci/hugo-plugin">GitHub →</a>

如果可能的话,谁能给我指出正确的 API 吗?

【问题讨论】:

  • 您是否尝试过使用 Chrome 中的选择器?
  • 是的,我实际上是从 Chrome 复制的
  • 你为什么用Jsoup.parse(link)而不是Jsoup.connect(link).get()

标签: java jsoup xsoup


【解决方案1】:

您是否尝试过类似的方法:

Document doc = Jsoup.parse("https://plugins.jenkins.io/hugo");    
Elements aTags = doc.select("a[data-reactid=\"30\"]");

它应该解析这个:&lt;a href="https://github.com/jenkinsci/hugo-plugin" data-reactid="30"&gt;GitHub →&lt;/a&gt;

然后从aTags 你可以做aTags.attr("href"),这应该给你URL。就是这样。

如果您看不到data-reactid,那么您可以执行divs = doc.select("div[col-md-4]"),然后从divs,您将获得a 标记和href 属性。我们的想法是从 HTML 标记和属性中找到独特的东西并定位它以获取 URL。

【讨论】:

  • 我没有那个选项,因为元素是&lt;a href="https://github.com/jenkinsci/hugo-plugin"&gt;GitHub →&lt;/a&gt;
  • 你为什么没有那个选项?如果我检查元素或视图源,我可以看到 data-reactid 属性。
【解决方案2】:

这应该是你要找的。​​p>

Elements githubLinks = doc.getElementsByAttributeValueStarting("href", "https://github.com/");
for(Element link : githubLinks) {
    System.out.println(link.attr("href"));
}

【讨论】:

    猜你喜欢
    • 2015-02-28
    • 1970-01-01
    • 1970-01-01
    • 2021-12-27
    • 1970-01-01
    • 2013-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多