HTML को प्लेन टेक्स्ट में बदलने के लिए jsoup का उपयोग करते समय मैं लाइन ब्रेक कैसे सुरक्षित रखता हूं?


101

मेरे पास निम्नलिखित कोड हैं:

 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)));
}

और मेरे पास परिणाम है:

hello world yo googlez

लेकिन मैं लाइन तोड़ना चाहता हूं:

hello world
yo googlez

मैंने jsoup के TextNode # getWholeText () को देखा है, लेकिन मैं इसका उपयोग कैसे कर सकता हूं, इसका पता नहीं लगा सकता।

यदि <br>मार्कअप आई पार्स में ए है , तो मैं अपने परिणामी आउटपुट में लाइन ब्रेक कैसे प्राप्त कर सकता हूं?


अपने पाठ को संपादित करें - आपके प्रश्न में कोई लाइन ब्रेक नहीं है। सामान्य तौर पर, कृपया पोस्ट करने से पहले अपने प्रश्न का पूर्वावलोकन पढ़ें, यह देखने के लिए कि सब कुछ सही दिखाई दे रहा है।
रॉबिन ग्रीन

मैंने एक ही सवाल पूछा (jsoup आवश्यकता के बिना), लेकिन मेरे पास अभी भी एक अच्छा समाधान नहीं है: stackoverflow.com/questions/2513707/…
Eduardo

देखें @zeenosaur का जवाब।
जंग-हो बा

जवाबों:


102

लाइनब्रीक को संरक्षित करने वाला वास्तविक समाधान इस तरह होना चाहिए:

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));
}

यह निम्नलिखित आवश्यकताओं को पूरा करता है:

  1. यदि मूल html में newline (\ n) शामिल है, तो यह संरक्षित हो जाता है
  2. यदि मूल html में br या p टैग हैं, तो वे newline (\ n) में अनुवादित हो जाते हैं।

5
यह चयनित जवाब होना चाहिए
duy

2
br2nl सबसे सहायक या सटीक विधि का नाम नहीं है
डीडी।

2
यह सबसे अच्छा जवाब है। लेकिन कैसे के बारे में for (Element e : document.select("br")) e.after(new TextNode("\n", ""));असली newline और नहीं अनुक्रम \ n? देखें नोड :: के बाद () और तत्वों :: संलग्न () अंतर के लिए। replaceAll()इस मामले में जरूरत नहीं है। पी और अन्य ब्लॉक तत्वों के लिए समान है।
user2043553 8

1
@ user121196 का उत्तर चुना हुआ उत्तर होना चाहिए। यदि आपके पास इनपुट HTML को साफ करने के बाद भी HTML इकाइयाँ हैं, तो StringEscapeUtils.unescapeHtml (...) अपाचे को Jsoup क्लीन से आउटपुट में लागू करें।
karth500

6
इस समस्या के व्यापक उत्तर के लिए github.com/jhy/jsoup/blob/master/src/main/java/org/jsoup/… देखें ।
मैल्कम स्मिथ

44
Jsoup.clean(unsafeString, "", Whitelist.none(), new OutputSettings().prettyPrint(false));

हम यहां इस विधि का उपयोग कर रहे हैं:

public static String clean(String bodyHtml,
                       String baseUri,
                       Whitelist whitelist,
                       Document.OutputSettings outputSettings)

इसे पास करके Whitelist.none()हम यह सुनिश्चित करते हैं कि सभी HTML हटा दिए गए हैं।

पास करने से new OutputSettings().prettyPrint(false)हम सुनिश्चित करते हैं कि आउटपुट में सुधार नहीं हुआ है और लाइन ब्रेक संरक्षित हैं।


यह एकमात्र सही उत्तर होना चाहिए। अन्य सभी मानते हैं कि केवल brटैग नई लाइनें उत्पन्न करते हैं। HTML में किसी भी अन्य ब्लॉक तत्व के बारे में क्या है div, जैसे p, ulआदि? ये सभी नई लाइनों को भी पेश करते हैं।
अदर्सहर

7
इस समाधान के साथ, HTML "<html> <body> <div> लाइन 1 </ div> <div> लाइन 2 </ div> <div> लाइन 3 </ div> </ body> </ html>" आउटपुट: कोई नई लाइनों के साथ "लाइन 1 पंक्ति 2 पंक्ति 3"।
JohnC

2
यह मेरे लिए काम नहीं करता है; <br> लाइन विराम नहीं बना रहे हैं।
जोशुआ

43

साथ में

Jsoup.parse("A\nB").text();

आपके पास आउटपुट है

"A B" 

और नहीं

A

B

इसके लिए मैं उपयोग कर रहा हूं:

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

2
वास्तव में यह एक आसान उपशामक है, लेकिन IMHO को पूरी तरह से स्वयं Jsoup पुस्तकालय द्वारा नियंत्रित किया जाना चाहिए (जो इस समय इस तरह के कुछ परेशान व्यवहार करता है - अन्यथा यह एक महान पुस्तकालय है!)।
एसआरजी

5
क्या JSoup आपको DOM नहीं देता है? क्यों न केवल सभी <br>तत्वों को नई नोड्स वाले टेक्स्ट नोड्स के साथ बदलें और फिर .text()एक रेगेक्स ट्रांसफॉर्म करने के बजाय कॉल करें जो कुछ स्ट्रिंग्स के लिए गलत आउटपुट का कारण बनेगा जैसे<div title=<br>'not an attribute'></div>
माइक सैमुअल

5
अच्छा लगा, लेकिन वह "डिस्क्रिप्शन" कहां से आता है?
स्टीव वाटर्स

"डिस्क्रिप्शन" उस चर का प्रतिनिधित्व करता है जो सादा पाठ को सौंपा गया है
enigma969

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));
}

अच्छा यह मुझे एक छोटे से बदलाव के साथ काम करता है new Document.OutputSettings().prettyPrint(true)
आशु

यह समाधान "& nbsp;" पाठ के रूप में एक अंतरिक्ष में उन्हें पार्स करने के बजाय।
आंद्रेई वोलगिन

13

Jsoup v1.11.2 पर, अब हम उपयोग कर सकते हैं Element.wholeText()

उदाहरण कोड:

String cleanString = Jsoup.parse(htmlString).wholeText();

user121196's जवाब अभी भी काम करता है। लेकिन wholeText()ग्रंथों के संरेखण को संरक्षित करता है।


सुपर-अच्छी सुविधा!
डेनिस कुलगिन

8

अधिक जटिल HTML के लिए उपरोक्त समाधानों में से किसी ने भी बहुत सही काम नहीं किया; रेखा को संरक्षित करने के दौरान मैं रूपांतरण को सफलतापूर्वक करने में सक्षम था:

Document document = Jsoup.parse(myHtml);
String text = new HtmlToPlainText().getPlainText(document);

(संस्करण 1.10.3)


1
सभी उत्तरों में से सर्वश्रेष्ठ! धन्यवाद एंडी रेस!
भारथ नादुक्ताला

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();               
}

और आपके कोड के लिए

String result = convertNodeToText(JSoup.parse(html))

मुझे लगता है कि आप अगर परीक्षण करना चाहिए isBlockमें tail(node, depth)बजाय, और संलग्न \nजब जब यह प्रवेश करने के बजाय ब्लॉक छोड़ने? मैं कर रहा हूँ कि (यानी का उपयोग tail) और वह ठीक काम करता है। हालाँकि अगर मैं headआपके जैसा उपयोग करता हूं, तो यह: <p>line one<p>line twoएक पंक्ति के रूप में समाप्त होता है।
KajMagnus

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

यदि html में "br2n" नहीं है तो काम करता है

इसलिए,

text = Jsoup.parse(html.replaceAll("(?i)<br[^>]*>", "<pre>\n</pre>")).text();

अधिक विश्वसनीय और आसान काम करता है।


4

Jsoup का उपयोग करके यह प्रयास करें:

    doc.outputSettings(new OutputSettings().prettyPrint(false));

    //select all <br> tags and append \n after that
    doc.select("br").after("\\n");

    //select all <p> tags and prepend \n before that
    doc.select("p").before("\\n");

    //get the HTML from the document, and retaining original new lines
    String str = doc.html().replaceAll("\\\\n", "\n");

3

textNodes()पाठ नोड्स की एक सूची प्राप्त करने के लिए उपयोग करें । फिर उन्हें \nविभाजक के रूप में समतल करें। यहाँ कुछ scala कोड का उपयोग किया गया है, जावा पोर्ट आसान होना चाहिए:

val rawTxt = doc.body().getElementsByTag("div").first.textNodes()
                    .asScala.mkString("<br />\n")

3

इस सवाल पर अन्य उत्तरों और टिप्पणियों के आधार पर ऐसा लगता है कि यहां आने वाले अधिकांश लोग वास्तव में एक सामान्य समाधान की तलाश कर रहे हैं जो HTML दस्तावेज़ के एक अच्छी तरह से स्वरूपित सादे पाठ प्रतिनिधित्व प्रदान करेगा। मुझे पता है कि मैं था।

सौभाग्य से JSoup पहले से ही इसे प्राप्त करने का एक बहुत व्यापक उदाहरण प्रदान करते हैं: HtmlToPlainText.java

उदाहरण FormattingVisitorको आसानी से आपकी प्राथमिकता के लिए ट्विक किया जा सकता है और अधिकांश ब्लॉक तत्वों और लाइन रैपिंग से संबंधित है।

लिंक सड़ने से बचने के लिए, यहाँ जोनाथन हेडली का समाधान पूर्ण है:

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();
        }
    }
}

3

यह html से पाठ में अनुवाद करने का मेरा संस्करण है (उपयोगकर्ता के संशोधित संस्करण12119696, वास्तव में)।

यह सिर्फ लाइन ब्रेक को संरक्षित नहीं करता है, बल्कि टेक्स्ट को फॉर्मेट करने और अत्यधिक लाइन ब्रेक को हटाने, HTML से बचने के प्रतीकों को भी दिखाता है, और आपको अपने HTML से बहुत बेहतर परिणाम मिलेगा (मेरे मामले में मैं इसे मेल से प्राप्त कर रहा हूं)।

यह मूल रूप से स्काला में लिखा गया है, लेकिन आप इसे आसानी से जावा में बदल सकते हैं

def html2text( rawHtml : String ) : String = {

    val htmlDoc = Jsoup.parseBodyFragment( rawHtml, "/" )
    htmlDoc.select("br").append("\\nl")
    htmlDoc.select("div").prepend("\\nl").append("\\nl")
    htmlDoc.select("p").prepend("\\nl\\nl").append("\\nl\\nl")

    org.jsoup.parser.Parser.unescapeEntities(
        Jsoup.clean(
          htmlDoc.html(),
          "",
          Whitelist.none(),
          new org.jsoup.nodes.Document.OutputSettings().prettyPrint(true)
        ),false
    ).
    replaceAll("\\\\nl", "\n").
    replaceAll("\r","").
    replaceAll("\n\\s+\n","\n").
    replaceAll("\n\n+","\n\n").     
    trim()      
}

आपको <div> टैग के लिए भी एक नई लाइन प्रस्तुत करने की आवश्यकता है। अन्यथा, यदि कोई div <a> या <span> टैग का अनुसरण करता है, तो यह एक नई पंक्ति में नहीं होगा।
आंद्रेई वोलगिन

2

इसे इस्तेमाल करे:

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

1
<p> <b> हैलो दुनिया </ b> </ p> <p> <br /> <b> यो </ b> <a href=" google.com"> googlez </a> </ p > लेकिन मुझे हेल्लो वर्ल्ड yo googlez (html टैग्स के बिना) की जरूरत है
बिली

यह उत्तर सादे पाठ को वापस नहीं करता है; यह HTML सम्मिलित किए गए newlines के साथ लौटाता है।
काजागमनस

1
/**
 * Recursive method to replace html br with java \n. The recursive method ensures that the linebreaker can never end up pre-existing in the text being replaced.
 * @param html
 * @param linebreakerString
 * @return the html as String with proper java newlines instead of br
 */
public static String replaceBrWithNewLine(String html, String linebreakerString){
    String result = "";
    if(html.contains(linebreakerString)){
        result = replaceBrWithNewLine(html, linebreakerString+"1");
    } else {
        result = Jsoup.parse(html.replaceAll("(?i)<br[^>]*>", linebreakerString)).text(); // replace and html line breaks with java linebreak.
        result = result.replaceAll(linebreakerString, "\n");
    }
    return result;
}

HTML में प्रश्न के साथ कॉल करके उपयोग किया जाता है, जिसमें br शामिल होता है, साथ ही साथ जो भी स्ट्रिंग आप उपयोग करना चाहते हैं वह अस्थायी newline प्लेसहोल्डर है। उदाहरण के लिए:

replaceBrWithNewLine(element.html(), "br2n")

पुनरावृत्ति यह सुनिश्चित करेगी कि आप जिस स्ट्रिंग का उपयोग newline / linebreaker प्लेसहोल्डर के रूप में करते हैं, वह वास्तव में स्रोत html में कभी नहीं होगा, क्योंकि यह "1" को जोड़ता रहेगा जब तक कि लिंकब्रेकर प्लेसहोल्डर स्ट्रिंग html में नहीं मिल जाता है। यह प्रारूपण मुद्दा नहीं है कि Jsoup.clean विधियाँ विशेष वर्णों के साथ मुठभेड़ करती हैं।


अच्छा एक, लेकिन आपको पुनरावृत्ति की आवश्यकता नहीं है, बस इस पंक्ति को जोड़ें: जबकि (गंदे HTML.contains (लाइनब्रेकरस्ट्रिंग)) लाइनब्रेकरस्ट्रिंग = लाइनब्रेकरस्ट्रिंग + "1";
डॉ। NotSoKind 15

आह येस। एकदम सच। लगता है मेरे मन में एक बार वास्तव में पुनरावृत्ति का उपयोग करने में सक्षम होने के लिए पकड़ा गया :)
Chris6647

1

User121196 और selects और <pre>s के साथ ग्रीन बेरेट के उत्तर के आधार पर , एकमात्र समाधान जो मेरे लिए काम करता है वह है:

org.jsoup.nodes.Element elementWithHtml = ....
elementWithHtml.select("br").append("<pre>\n</pre>");
elementWithHtml.select("p").prepend("<pre>\n\n</pre>");
elementWithHtml.text();
हमारी साइट का प्रयोग करके, आप स्वीकार करते हैं कि आपने हमारी Cookie Policy और निजता नीति को पढ़ और समझा लिया है।
Licensed under cc by-sa 3.0 with attribution required.