Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jSoup to get text from <span> class

I have a part of the HTML file with the following format:

<h6 class="uiStreamMessage" data-ft="_____"> 
   <span class="messageBody" data-ft="____"> Welcome
   </span>
</h6>

In the file, there are other span classes. But I would like to get the text for ALL 'messageBody' span only, which will be inserted into the database.

I've tried:

Elements links = doc.select("span.messageBody");
for (Element link : links) {
     message = link.text();
     // codes to insert into DB
}

and even

Elements links = doc.select("h6.uiStreamMessage span.messageBody");

Both doesn't work. I couldn't find any solutions from elsewhere. Please kindly help.

**EDIT

I've realised it's a nested span within the html file:

<h6 class="uiStreamMessage" data-ft=""> 
   <span class="messageBody" data-ft="">Twisted<a href="http://"><span>http://</span>
   <span class="word_break"></span>www.tb.net/</a> Balloons
   </span>
</h6>

And it's only at times there is another span within the 'messageBody' span. How do I get ALL the text within the 'messageBody' span?

like image 891
Jo S. Avatar asked Dec 27 '22 04:12

Jo S.


1 Answers

 String html = "<h6 class='uiStreamMessage' data-ft=''><span class='messageBody' data-ft=''>Twisted<a href='http://'><span>http://</span><span class='word_break'></span>www.tb.net/</a> Balloons</span></h6>";
 Document doc = Jsoup.parse(html);
 Elements elements = doc.select("h6.uiStreamMessage > span.messageBody");
 for (Element e : elements) {
      System.out.println("All text:" + e.text());
      System.out.println("Only messageBody text:" + e.ownText());
}

For the facebook page https://www.facebook.com/pages/The-Nanyang-Chronicle/141387533074:

try {
        Document doc = Jsoup.connect("https://www.facebook.com/pages/The-Nanyang-Chronicle/141387533074").timeout(0).get();

        Elements elements = doc.select("code.hidden_elem");
        for (Element e : elements) {
            String eHtml = e.html().replace("<!--", "").replace("-->", "");
            Document eWIthoutComment = Jsoup.parse(eHtml);
            Elements elem = eWIthoutComment.select("h6.uiStreamMessage >span.messageBody");
            for (Element eb : elem) {
                System.out.println(eb.text());                   
            }
        }
    } catch (IOException ex) {
        System.err.println("Error:" + ex.getMessage());
    }
like image 89
Rodri_gore Avatar answered Jan 12 '23 02:01

Rodri_gore