【问题标题】:How can you parse HTML in android?你怎么能在android中解析HTML?
【发布时间】:2011-08-18 21:20:04
【问题描述】:

我正在为 android 创建一个应用程序,该应用程序的一个功能元素是返回在线搜索图书馆目录的结果。应用程序需要以与应用程序的其余部分保持一致的方式显示搜索结果,这是通过自定义 HTML 表单执行的。即,需要解析搜索结果并显示有用的元素。我只是想知道这是否/如何在 android 中实现?

【问题讨论】:

    标签: android html xml parsing


    【解决方案1】:

    您将使用 Html 解析器。我使用并且效果很好的一个是JSoup 这是您需要开始解析 html 的地方。 Apache Jericho 也是另一个不错的选择。

    您将使用 DOM 检索 html 文档,并使用 JSOUP Select() 方法选择您想要获取的任何标签。通过标签、id 或类。

    解决方案

    Use the: Jsoup.connect(String url) method:
    
     Document doc = Jsoup.connect("http://example.com/").get();
    

    这将允许您使用 url 连接到 html 页面。并将其存储为 Document doc,通过 DOM。并使用 selector() 方法从中读取。

    说明

    connect(String url) 方法创建一个新的 Connection,然后 get() 获取并解析 HTML 文件。如果在提取时发生错误 URL,它会抛出一个 IOException,你应该处理它 适当的。

    Connection 接口是为方法链而设计的 具体要求:

     Document doc = Jsoup.connect("http://example.com")
    

    如果您通读 Jsoup 上的文档,您应该能够做到这一点。

    编辑:这里是你将如何使用选择器方法

      //Once the Document is retrieved above, use these selector methods to Extract the   data you want by using the tags, id, or css class 
    
      Elements links = doc.select("a[href]"); // a with href
      Elements pngs = doc.select("img[src$=.png]");
      // img with src ending .png
    
      Element masthead = doc.select("div.masthead").first();
      // div with class=masthead
    
      Elements resultLinks = doc.select("h3.r > a"); // direct a after h3
    

    编辑:使用 JSOUP,您可以使用它来获取属性、文本,

    Document doc = Jsoup.connect("http://example.com")
    Element link = doc.select("a").first();
    
    String text = doc.body().text(); // "An example link"
    String linkHref = link.attr("href"); // "http://example.com/"
    String linkText = link.text(); // "example""
    
    String linkOuterH = link.outerHtml(); 
    // "<a href="http://example.com"><b>example</b></a>"
    String linkInnerH = link.html(); // "<b>example</b>"
    

    【讨论】:

      【解决方案2】:

      您可以使用 XmlPullParser 来解析 XML。

      例如参考http://developer.android.com/reference/org/xmlpull/v1/XmlPullParser.html

      【讨论】:

      • HTML 不是 XML,尤其是 HTML5,带有
        等自闭合标签。我永远不会用 XML 解析器解析它。
      【解决方案3】:

      由于搜索结果是 HTML 并且 HTML 是一种标记语言 (ML),您可以使用 Android 的 XmlPullParser 来解析结果。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2010-10-20
        • 2018-07-26
        • 2013-04-18
        • 2015-11-08
        • 1970-01-01
        • 2022-06-14
        相关资源
        最近更新 更多