【问题标题】:how to get proper formatted text from html when tags don't have line breaks标签没有换行符时如何从html中获取正确的格式化文本
【发布时间】:2014-02-24 15:11:59
【问题描述】:

我正在尝试借助 Jsoup HTML 解析库来解析这个示例 html 文件。

 <html>
 <body>
 <p> this is sample text</p>
 <h1>this is heading sample</h1>
 <select name="car" size="1">
 <option  value="Ford">Ford</option><option  value="Chevy">Chevy</option><option selected value="Subaru">Subaru</option>
 </select>
 <p>this is second sample text</p>
 </body>
 </html>

当我只提取文本时,我得到以下信息。

this is sample text this is heading sample FordChevySubaru this is second sample text

选项标签文本中没有空格或换行符。

如果 html 是这样的

<html>
 <body>
 <p> this is sample text</p>
 <h1>this is heading sample</h1>
 <select name="car" size="1">
 <option  value="Ford">Ford</option>
 <option  value="Chevy">Chevy</option>
 <option selected value="Subaru">Subaru</option>
 </select>
 <p>this is second sample text</p>
 </body>
 </html>

现在在这种情况下,文本是这样的

this is sample text this is heading sample Ford Chevy Subaru this is second sample text

在选项标签的文本中有适当的空格。如何使用第一个 html 文件获得第二个输出。即如果标签中没有换行符,字符串怎么可能没有连接起来。

我在 Java 中使用以下代码。

 public static String extractText(File file) throws IOException {

    Document document = Jsoup.parse(file,null);
    Element body=document.body();
    String textOnly=body.text();
    return textOnly;
    }

【问题讨论】:

    标签: java html-parsing jsoup information-retrieval


    【解决方案1】:

    我认为满足您要求的唯一解决方案是遍历 DOM 并打印文本节点:

    public static String extractText(File file) throws IOException {
        StringBuilder sb = new StringBuilder();
        Document document = Jsoup.parse(file, null);
        Elements body = document.getAllElements();
        for (Element e : body) {
            for (TextNode t : e.textNodes()) {
                String s = t.text();
                if (StringUtils.isNotBlank(s))
                    sb.append(t.text()).append(" ");
            }
        }
        return sb.toString();
    }
    

    希望对你有帮助。

    【讨论】:

      猜你喜欢
      • 2016-05-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-25
      • 2015-11-21
      • 1970-01-01
      • 2015-02-14
      • 1970-01-01
      相关资源
      最近更新 更多