【问题标题】:How to parse HTML Heading如何解析 HTML 标题
【发布时间】:2011-09-23 02:47:14
【问题描述】:

我正在解析这个 HTML。

<div id="articleHeader">
<h1 class="headline">Assassin's Creed Revelations: The Three Heroes</h1>
<h2 class="subheadline">Exclusive videos and art spanning three eras of assassins.</h2>
<h2 class="publish-date"><script>showUSloc=(checkLocale('uk')||checkLocale('au'));document.writeln(showUSloc ? '<strong>US, </strong>' : '');</script>

<span class="us_details">September 22, 2011</span>

我想做的是解析“标题”副标题并将日期全部发布到单独的字符串中

【问题讨论】:

标签: java android html-parsing jsoup


【解决方案1】:

只需使用正确的CSS selectors 即可获取它们。

Document document = Jsoup.connect(url).get();
String headline = document.select("#articleHeader .headline").text();
String subheadline = document.select("#articleHeader .subheadline").text();
String us_details = document.select("#articleHeader .us_details").text();
// ...

或者更高效一点:

Document document = Jsoup.connect(url).get();
Element articleHeader = document.select("#articleHeader").first();
String headline = articleHeader.select(".headline").text();
String subheadline = articleHeader.select(".subheadline").text();
String us_details = articleHeader.select(".us_details").text();
// ...

【讨论】:

    【解决方案2】:

    Android 有一个 SAX parser built into it 。您也可以使用其他标准 XML 解析器。

    但我认为如果你的 HTML 足够简单,你可以使用 RegEx 来提取字符串。

    【讨论】:

    • 正则表达式? 不寒而栗。你错过了jsoup标签吗?
    • 是的,我确实想念 jsoup,我喜欢 RegEx
    • 我也喜欢正则表达式。但是,要解析 HTML?完全错误的工具。
    • 不是解析而是从文本中获取一些特定的数据。有时这种方式更简单
    猜你喜欢
    • 2019-02-16
    • 1970-01-01
    • 2020-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-20
    • 1970-01-01
    • 2011-07-21
    相关资源
    最近更新 更多