使用jsoup将html转换为纯文本时如何保留换行符?

Bil*_*lly 95 java jsoup

我有以下代码:

 public class NewClass {
     public String noTags(String str){
         return Jsoup.parse(str).text();
     }


     public static void main(String args[]) {
         String strings="<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN \">" +
         "<HTML> <HEAD> <TITLE></TITLE> <style>body{ font-size: 12px;font-family: verdana, arial, helvetica, sans-serif;}</style> </HEAD> <BODY><p><b>hello world</b></p><p><br><b>yo</b> <a href=\"http://google.com\">googlez</a></p></BODY> </HTML> ";

         NewClass text = new NewClass();
         System.out.println((text.noTags(strings)));
}
Run Code Online (Sandbox Code Playgroud)

我有结果:

hello world yo googlez
Run Code Online (Sandbox Code Playgroud)

但我想打破界限:

hello world
yo googlez
Run Code Online (Sandbox Code Playgroud)

我查看了jsoup的TextNode#getWholeText()但我无法弄清楚如何使用它.

如果<br>我解析了标记中的a ,那么如何在结果输出中获得换行符?

use*_*196 92

保留换行符的真正解决方案应该是这样的:

public static String br2nl(String html) {
    if(html==null)
        return html;
    Document document = Jsoup.parse(html);
    document.outputSettings(new Document.OutputSettings().prettyPrint(false));//makes html() preserve linebreaks and spacing
    document.select("br").append("\\n");
    document.select("p").prepend("\\n\\n");
    String s = document.html().replaceAll("\\\\n", "\n");
    return Jsoup.clean(s, "", Whitelist.none(), new Document.OutputSettings().prettyPrint(false));
}
Run Code Online (Sandbox Code Playgroud)

它满足以下要求:

  1. 如果原始html包含换行符(\n),则会保留它
  2. 如果原始html包含br或p标签,它们将被转换为换行符(\n).

  • 这应该是选定的答案 (4认同)
  • 有关此问题的全面答案,请参阅https://github.com/jhy/jsoup/blob/master/src/main/java/org/jsoup/examples/HtmlToPlainText.java. (4认同)
  • br2nl不是最有用或最准确的方法名称 (2认同)
  • 这是最好的答案。但是`for (Element e : document.select("br")) e.after(new TextNode("\n", ""));` 附加真正的换行符而不是序列 \n 怎么样?参见 [Node::after()](http://jsoup.org/apidocs/org/jsoup/nodes/Node.html#after%28org.jsoup.nodes.Node%29) 和 [Elements::append() ](http://jsoup.org/apidocs/org/jsoup/select/Elements.html#append%28java.lang.String%29) 区别。在这种情况下不需要`replaceAll()`。p 和其他块元素类似。 (2认同)

Pau*_*s Z 43

Jsoup.clean(unsafeString, "", Whitelist.none(), new OutputSettings().prettyPrint(false));
Run Code Online (Sandbox Code Playgroud)

我们在这里使用这种方法:

public static String clean(String bodyHtml,
                       String baseUri,
                       Whitelist whitelist,
                       Document.OutputSettings outputSettings)
Run Code Online (Sandbox Code Playgroud)

通过传递它,Whitelist.none()我们确保删除所有HTML.

通过传递,new OutputSettings().prettyPrint(false)我们确保不重新格式化输出并保留换行符.

  • 使用此解决方案,html"<html> <body> <div>第1行</ div> <div>第2行</ div> <div>第3行</ div> </ body> </ html>"生成输出:"line 1line 2line 3",没有新行. (7认同)
  • 这对我不起作用;&lt;br&gt;不会创建换行符。 (2认同)

Mir*_*chi 42

Jsoup.parse("A\nB").text();
Run Code Online (Sandbox Code Playgroud)

你有输出

"A B" 
Run Code Online (Sandbox Code Playgroud)

并不是

A

B
Run Code Online (Sandbox Code Playgroud)

为此,我正在使用:

descrizione = Jsoup.parse(html.replaceAll("(?i)<br[^>]*>", "br2n")).text();
text = descrizione.replaceAll("br2n", "\n");
Run Code Online (Sandbox Code Playgroud)

  • 不是JSoup给你一个DOM吗?为什么不直接用包含新行的文本节点替换所有```元素,然后调用`.text()`而不是进行正则表达式转换,这将导致某些字符串的输出不正确,如`<div title = <br>'不是属性'> </ div>` (5认同)
  • 很好,但那个"describezione"来自哪里? (5认同)
  • 确实这是一个简单的姑息,但恕我直言,这应该由Jsoup图书馆本身完全处理(此时有一些像这样的令人不安的行为 - 否则它是一个很棒的图书馆!). (2认同)

小智 23

使用jsoup尝试这个:

public static String cleanPreserveLineBreaks(String bodyHtml) {

    // get pretty printed html with preserved br and p tags
    String prettyPrintedBodyFragment = Jsoup.clean(bodyHtml, "", Whitelist.none().addTags("br", "p"), new OutputSettings().prettyPrint(true));
    // get plain text with preserved line breaks by disabled prettyPrint
    return Jsoup.clean(prettyPrintedBodyFragment, "", Whitelist.none(), new OutputSettings().prettyPrint(false));
}
Run Code Online (Sandbox Code Playgroud)


zee*_*aur 10

在Jsoup v1.11.2上,我们现在可以使用Element.wholeText()

示例代码:

String cleanString = Jsoup.parse(htmlString).wholeText();
Run Code Online (Sandbox Code Playgroud)

user121196's 答案仍然有效。但是wholeText()保留文本的对齐方式。


And*_*Res 9

对于更复杂的 HTML,上述解决方案都不是很正确;我能够成功地进行转换,同时保留换行符:

Document document = Jsoup.parse(myHtml);
String text = new HtmlToPlainText().getPlainText(document);
Run Code Online (Sandbox Code Playgroud)

(版本 1.10.3)


pop*_*rny 6

您可以遍历给定元素

public String convertNodeToText(Element element)
{
    final StringBuilder buffer = new StringBuilder();

    new NodeTraversor(new NodeVisitor() {
        boolean isNewline = true;

        @Override
        public void head(Node node, int depth) {
            if (node instanceof TextNode) {
                TextNode textNode = (TextNode) node;
                String text = textNode.text().replace('\u00A0', ' ').trim();                    
                if(!text.isEmpty())
                {                        
                    buffer.append(text);
                    isNewline = false;
                }
            } else if (node instanceof Element) {
                Element element = (Element) node;
                if (!isNewline)
                {
                    if((element.isBlock() || element.tagName().equals("br")))
                    {
                        buffer.append("\n");
                        isNewline = true;
                    }
                }
            }                
        }

        @Override
        public void tail(Node node, int depth) {                
        }                        
    }).traverse(element);        

    return buffer.toString();               
}
Run Code Online (Sandbox Code Playgroud)

并为您的代码

String result = convertNodeToText(JSoup.parse(html))
Run Code Online (Sandbox Code Playgroud)


Mal*_*ith 5

根据其他答案和对此问题的评论,似乎大多数来这里的人确实在寻找一个通用的解决方案,该解决方案将提供 HTML 文档的格式良好的纯文本表示形式。我知道我是。

幸运的是,JSoup 已经提供了一个非常全面的示例来说明如何实现这一点:HtmlToPlainText.java

该示例FormattingVisitor可以轻松地根据您的喜好进行调整,并处理大多数块元素和换行。

为了避免链接失效,以下是Jonathan Hedley的完整解决方案:

package org.jsoup.examples;

import org.jsoup.Jsoup;
import org.jsoup.helper.StringUtil;
import org.jsoup.helper.Validate;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
import org.jsoup.nodes.TextNode;
import org.jsoup.select.Elements;
import org.jsoup.select.NodeTraversor;
import org.jsoup.select.NodeVisitor;

import java.io.IOException;

/**
 * HTML to plain-text. This example program demonstrates the use of jsoup to convert HTML input to lightly-formatted
 * plain-text. That is divergent from the general goal of jsoup's .text() methods, which is to get clean data from a
 * scrape.
 * <p>
 * Note that this is a fairly simplistic formatter -- for real world use you'll want to embrace and extend.
 * </p>
 * <p>
 * To invoke from the command line, assuming you've downloaded the jsoup jar to your current directory:</p>
 * <p><code>java -cp jsoup.jar org.jsoup.examples.HtmlToPlainText url [selector]</code></p>
 * where <i>url</i> is the URL to fetch, and <i>selector</i> is an optional CSS selector.
 * 
 * @author Jonathan Hedley, jonathan@hedley.net
 */
public class HtmlToPlainText {
    private static final String userAgent = "Mozilla/5.0 (jsoup)";
    private static final int timeout = 5 * 1000;

    public static void main(String... args) throws IOException {
        Validate.isTrue(args.length == 1 || args.length == 2, "usage: java -cp jsoup.jar org.jsoup.examples.HtmlToPlainText url [selector]");
        final String url = args[0];
        final String selector = args.length == 2 ? args[1] : null;

        // fetch the specified URL and parse to a HTML DOM
        Document doc = Jsoup.connect(url).userAgent(userAgent).timeout(timeout).get();

        HtmlToPlainText formatter = new HtmlToPlainText();

        if (selector != null) {
            Elements elements = doc.select(selector); // get each element that matches the CSS selector
            for (Element element : elements) {
                String plainText = formatter.getPlainText(element); // format that element to plain text
                System.out.println(plainText);
            }
        } else { // format the whole doc
            String plainText = formatter.getPlainText(doc);
            System.out.println(plainText);
        }
    }

    /**
     * Format an Element to plain-text
     * @param element the root element to format
     * @return formatted text
     */
    public String getPlainText(Element element) {
        FormattingVisitor formatter = new FormattingVisitor();
        NodeTraversor traversor = new NodeTraversor(formatter);
        traversor.traverse(element); // walk the DOM, and call .head() and .tail() for each node

        return formatter.toString();
    }

    // the formatting rules, implemented in a breadth-first DOM traverse
    private class FormattingVisitor implements NodeVisitor {
        private static final int maxWidth = 80;
        private int width = 0;
        private StringBuilder accum = new StringBuilder(); // holds the accumulated text

        // hit when the node is first seen
        public void head(Node node, int depth) {
            String name = node.nodeName();
            if (node instanceof TextNode)
                append(((TextNode) node).text()); // TextNodes carry all user-readable text in the DOM.
            else if (name.equals("li"))
                append("\n * ");
            else if (name.equals("dt"))
                append("  ");
            else if (StringUtil.in(name, "p", "h1", "h2", "h3", "h4", "h5", "tr"))
                append("\n");
        }

        // hit when all of the node's children (if any) have been visited
        public void tail(Node node, int depth) {
            String name = node.nodeName();
            if (StringUtil.in(name, "br", "dd", "dt", "p", "h1", "h2", "h3", "h4", "h5"))
                append("\n");
            else if (name.equals("a"))
                append(String.format(" <%s>", node.absUrl("href")));
        }

        // appends text to the string builder with a simple word wrap method
        private void append(String text) {
            if (text.startsWith("\n"))
                width = 0; // reset counter if starts with a newline. only from formats above, not in natural text
            if (text.equals(" ") &&
                    (accum.length() == 0 || StringUtil.in(accum.substring(accum.length() - 1), " ", "\n")))
                return; // don't accumulate long runs of empty spaces

            if (text.length() + width > maxWidth) { // won't fit, needs to wrap
                String words[] = text.split("\\s+");
                for (int i = 0; i < words.length; i++) {
                    String word = words[i];
                    boolean last = i == words.length - 1;
                    if (!last) // insert a space if not the last word
                        word = word + " ";
                    if (word.length() + width > maxWidth) { // wrap and reset counter
                        accum.append("\n").append(word);
                        width = word.length();
                    } else {
                        accum.append(word);
                        width += word.length();
                    }
                }
            } else { // fits as is, without need to wrap text
                accum.append(text);
                width += text.length();
            }
        }

        @Override
        public String toString() {
            return accum.toString();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)


man*_*nji 3

尝试这个:

public String noTags(String str){
    Document d = Jsoup.parse(str);
    TextNode tn = new TextNode(d.body().html(), "");
    return tn.getWholeText();
}
Run Code Online (Sandbox Code Playgroud)