JSOUP:无法解析方法title()。

3

我正在尝试在Android项目中使用Jsoup,但是出现了错误。我正在使用Android Studio。我已将jsoup jar 1.8.2添加到libs文件夹中,并在build.gradle文件中添加了compile files('libs/jsoup-1.8.2.jar')这一行。奇怪的是,我在Eclipse中没有遇到任何类似的问题。有什么建议吗?谢谢!

protected Void doInBackground(Void... params) {
    try {
               // Connect to website
                Document document = (Document) Jsoup.connect("http://www.example.com/").get();
                // Get the html document title
                websiteTitle = document.title();
                Elements description = document.select("meta[name=description]");
                // Locate the content attribute
                websiteDescription = description.attr("content");
            } catch (IOException e) {
                e.printStackTrace();
    }
    return null;
}

PS:对于select方法,也会出现"Cannot resolve method 'select(java.lang.String)'"的错误。


你具体遇到了哪个错误?请将完整的堆栈跟踪编辑到你的问题中。 - TimoStaudinger
@TimoSta,我添加了一些更多的信息,我只有在调用select和title函数时才会出现错误。 - varunkr
看看我的答案! - TimoStaudinger
1个回答

2
你会收到错误,是因为一个 JSoup 的 Document 没有 select(String) 方法,而你正在尝试调用它。
相反,你应该 访问头部,它由一个 Element 表示,它允许你 select()
Elements description = document.head().select("meta[name=description]");

顺便提一下,不需要将其显式转换为Document
Document document = (Document) Jsoup.connect("http://www.example.com/").get();

`get()`方法已经返回了一个`Document`,你可以在食谱API文档中看到。

谢谢回复。但是关于无法解析方法标题的错误怎么办?另外,我将其转换为document类型,因为在那里也出现了错误,错误信息是:不兼容的类型:需要 org.w3c.dom.Document,找到的是 org.jsoup.nodes.Document。 - varunkr
1
你导入了哪个 Document?请确保导入的是 org.jsoup.nodes.Document。如果使用 org.w3c.dom.Document,它将无法正常工作。 - TimoStaudinger
我的错,那是我犯的一个愚蠢错误。不过还是谢谢你抽出时间来。 - varunkr

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接