【问题标题】:How can I read h3 and after text element with Jsoup?如何使用 Jsoup 读取 h3 和之后的文本元素?
【发布时间】:2019-09-02 12:59:12
【问题描述】:

我想阅读<h3><h3> 之间的文本,所以我想创建一个json 模型,如标题:文本、文本、h3 文本和没有广告的文本。

{
  "title": "text,text,text",
  "title": "text",
  "title": "text",
  ...
}

在这种情况下,我如何使用 Java 或 Kotlin 做到这一点?

<div class="biri" id="biri">
    <h1>Yoksa Birisi mi itti?</h1>
    <h3>Title</h3>Text,
    <br>Text,
    <br>Text.
    <h3>Title:</h3>Text
    <h3>Title:</h3>Text
    <div class="ad">
        <div style="max-width:336px;">
            <script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
            <ins class="adsbygoogle" style="display:block" data-ad-client="ca-pub-7180771993103993" data-ad-slot="2897611612" data-ad-format="auto"></ins>
            <script>
                (adsbygoogle = window.adsbygoogle || []).push({});
            </script>
        </div>
    </div>
    <h3>Title</h3>Text:
    <b>Text:</b> (Text
    <br>
</div>

【问题讨论】:

    标签: java html jsoup


    【解决方案1】:

    使用Document.select()可以获取所有h3标签:

    Document doc = Jsoup.parse(html);
    List<String> h3s = doc.select("h3").stream()
            .map(Element::text)
            .collect(Collectors.toList());
    

    这会提取所有h3 标签的内容并收集它们的内容。结果是这样的:

    [Title, Title:, Title:, Title]
    

    除此之外,您要创建的 JSON 无效,因为 JSON 对象中的键必须是唯一的,因此您不能有多个 h3 键。

    【讨论】:

    • "Title": "Text,Text,Text" 不可能吗?
    • “文本,文本,文本”不在 h3 元素中。
    • 不,这个 html 是不可能的。如果内容没有改变,你也许可以使用正则表达式。
    猜你喜欢
    • 1970-01-01
    • 2012-09-11
    • 1970-01-01
    • 2015-05-28
    • 2016-04-13
    • 1970-01-01
    • 1970-01-01
    • 2011-10-18
    • 2018-07-27
    相关资源
    最近更新 更多