【问题标题】:android html download and parse errorandroid html下载和解析错误
【发布时间】:2011-01-18 11:46:09
【问题描述】:

我正在尝试使用页面的 ul 下载 html 文件。我正在使用 Jsoup。 这是我的代码:

TextView ptext = (TextView) findViewById(R.id.pagetext);
    Document doc = null;
    try {
         doc = (Document) Jsoup.connect(mNewLinkUrl).get();
    } catch (IOException e) {
        Log.d(TAG, e.toString());
        e.printStackTrace();
    }
    NodeList nl = doc.getElementsByTagName("meta");
    Element meta = (Element) nl.item(0); 
    String title = meta.attr("title"); 
    ptext.append("\n" + mNewLinkUrl);

运行它时,我收到一条错误消息,提示未为 type 元素定义 attr。 我做错了什么?如果这看起来微不足道,请原谅我。

【问题讨论】:

    标签: android html jsoup


    【解决方案1】:

    确保Element 指的是org.jsoup.nodes.Element,而不是别的东西。验证您的导入。还要确保Document 引用org.jsoup.nodes.Document。它没有getElementsByTagName() 方法。 Jsoup 不使用任何 org.w3c.dom API。

    这是一个正确导入的完整示例:

    package com.stackoverflow.q4720189;
    
    import org.jsoup.Jsoup;
    import org.jsoup.nodes.Document;
    import org.jsoup.nodes.Element;
    
    public class Test {
    
        public static void main(String[] args) throws Exception {
            Document document = Jsoup.connect("http://example.com").get();
            Element firstMeta = document.select("meta").first();
            String title = firstMeta.attr("title"); 
            // ...
        }
    
    }
    

    【讨论】:

    • 由于当前接受的答案是错误的,我很乐意添加正确的答案,以避免在查询中遇到此问题的其他人被置于错误的轨道上。
    【解决方案2】:

    据我了解,这里的元素是org.w3c.dom.Element。然后使用meta.getAttribute() 而不是attr。元素类根本没有这种方法。

    【讨论】:

    • 抱歉,我使用的是 android.sax.Element。谢谢你的回复。
    猜你喜欢
    • 1970-01-01
    • 2014-10-24
    • 2016-09-04
    • 1970-01-01
    • 2010-11-26
    • 1970-01-01
    • 1970-01-01
    • 2014-12-19
    • 1970-01-01
    相关资源
    最近更新 更多