【问题标题】:strange jsoup behavior when getting first element获取第一个元素时奇怪的jsoup行为
【发布时间】:2016-10-05 21:14:35
【问题描述】:

我是 jsoup 的新手,所以我不知道为什么会出现以下内容:

...
Document doc = Jsoup.connect("http://4pda.ru").get();
Elements articleElems = doc.select("article.post");
for(Element article:articleElems)
{
    Element desc = article.select("div.description").first();
    Elements posts = desc.select("h1.list-post-title");
    Log.d(TAG,"size is "+posts.size()); // it's ok, size is 1
    ...
}

所以,由于大小为 1,我想获得第一个元素,我将代码更改如下:

for(Element article:articleElems)
{
     Element desc = article.select("div.description").first();
     Element post = desc.select("h1.list-post-title").first();
     Log.d(TAG,"post is "+post.toString()); // there NullPointerException throws
     ...
}

我无法理解...

【问题讨论】:

  • 是的,这看起来很奇怪。请同时添加连接源代码。
  • @F.Klein 有:Document doc = Jsoup.connect("http://4pda.ru").get(); Elements articleElems = doc.select("article.post");

标签: android exception jsoup


【解决方案1】:

您正在选择没有h1.list-post-title的文章
您可以使用has()。这是关于has()的官方文档
:has(seletor): find elements that contain elements matching the selector

这里是 has 的解决方案

    Document doc = Jsoup.connect("http://4pda.ru").get();
    Elements articleElems = doc.select("article.post:has(h1.list-post-title)");
    for (Element article : articleElems) {
        Element desc = article.select("div.description").first();
        Element post = desc.select("h1.list-post-title").first();
        System.out.println(post);
    }

【讨论】:

    猜你喜欢
    • 2016-07-24
    • 2018-08-07
    • 1970-01-01
    • 2011-12-04
    • 1970-01-01
    • 2021-10-27
    • 1970-01-01
    • 2018-02-18
    • 1970-01-01
    相关资源
    最近更新 更多