JSoup to get text from the <span> class
I have a part of an HTML file with the following format:
<h6 class="uiStreamMessage" data-ft="_____"> <span class="messageBody" data-ft="____"> Welcome </span> </h6> There are other span classes in the file. But I would like to get the text only for the range ALL 'messageBody', which will be inserted into the database.
I 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 do not work. I could not find any solutions from other sources. Please, kindly help.
** EDIT
I realized that this is a nested range in 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 that only from time to time there is a different range within the range of messageBody. How to get ALL text within a messageBody range?
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 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()); } Not sure why it is not working for you. Here is my code. It prints Welcome to the console.
String html = "<h6 class=\"uiStreamMessage\" data-ft=\"_____\">" + "<span class=\"messageBody\" data-ft=\"____\"> Welcome</span>" + "</h6>"; Document doc = Jsoup.parse(html); for (Element e : doc.select("span.messageBody")) { System.out.println(e.text()); } This is essentially the same code that you have, so there should be something else here.