I have html document

<HTML xmlns:OG="http://opengraphprotocol.org/schema/" xmlns:FB="http://www.facebook.com/2008/fbml"> <style type="text/css"></style> <BODY> <DIV class="block0"> <DIV class="pad0"> <DIV class="fblock"> <DIV class="block61"> <DIV class="rpad"> <H1 class="title">Во Франции по подозрению в планировании теракта задержали двух девушек</H1> <SPAN class="dt2">Понедельник, 26 сентября 2016, 16:08</SPAN> <DIV class="text"> <P>Во французском городе Ницца по подозрению в планировании теракта были задержаны двое девушек.</P> <P>Об этом сообщает <A href="https://www.afp.com">AFP</A>.</P> <P>Девушки в возрасте 17 и 18 лет подозреваются в планировании террористического нападения под руководством французского джихадиста Рашида Кассима.</P> <P>Подростки рассказали следователям, что они планировали нападение под влиянием Рашида Кассима, который сейчас находится в Сирии или Ираке, на территории, которая контролируется террористической организацией &quot;Исламское государство&quot;.</P> <P>Рашид Кассим, по мнению следователей, играет роль подстрекателя или спонсора, фактически призывая потенциальных террористов к совершению джихада во Франции.</P> <P>Стоит добавить, что во время обыска в помещениях, которые принадлежат задержанными, стражи порядка не нашли оружия.</P> <P>Издание отмечает, что девушки живут в том же районе, что и <A href="/rus/news/2016/07/15/7052184/">Мохамед Лахуайедж-Бухлель, убивший 86 человек</A> в Ницце 14 июля.</P> <P>Напомним, недавно французская <A href="/rus/news/2016/09/14/7054550/">полиция задержала подростка</A>, подозреваемого в подготовке теракта в Париже.</P> </DIV> <DIV class="btit4"><SPAN>ЧИТАЙ ТАКЖЕ</SPAN></DIV> </DIV> </DIV> </DIV> </DIV> </DIV> </BODY> </HTML> 

With the help of JSOUPa, I wanted to get all the "parents" of the title

 Element element = Jsoup.parse(html).getElementsByClass("title").parents().last(); System.out.println(element); 

In the console, I got the same HTML document. But I only need to get the "parents" heading. without unnecessary tags like this:

 <HTML xmlns:OG="http://opengraphprotocol.org/schema/" xmlns:FB="http://www.facebook.com/2008/fbml"> <BODY> <DIV class="block0"> <DIV class="pad0"> <DIV class="fblock"> <DIV class="block61"> <DIV class="rpad"> <H1 class="title">ЗАГОЛОВОК СТАТЬИ</H1> </DIV> </DIV> </DIV> </DIV> </DIV> </BODY> </HTML> 

What can you do about it?

And another question: how to find the title the title tag is there will be called not “title”, but something else for example: “head_article”. as pars HTML I will be from different sites.

  • what mean хотел получить всех "родителей" заголовка ? can you somehow say a little more clearly? Want to put them in the list or what? - Alexey Shimansky
  • @ Alexey Shimansky in the final result I need to get this: <HTML xmlns: OG = " opengraphprotocol.org/schema " xmlns: FB = " facebook.com/2008/fbml "> <BODY> <DIV class = "block0"> < DIV class = "pad0"> <DIV class = "fblock"> <DIV class = "block61"> <DIV class = "rpad"> <H1 class = "title"> ARTICLE HEADING </ H1> </ DIV> < / DIV> </ DIV> </ DIV> </ DIV> </ BODY> </ HTML> without unnecessary tags and without content - drugs_and_code
  • will the header always be first in the <DIV class="rpad"> block? - Alexey Shimansky
  • not. these will be different sites. I took this HTML for an example. - drugs_and_code
  • Well, then there is nothing to help, if the html is different, if the class of the header is different, by what criteria, then look for the title in general, if it may not even be in the h1 tag? that is, you want to parse the title without knowing where it may be in principle. sounds crazy - Alexey Shimansky

1 answer 1

Based only on this example, everything is simple:

  • take the element that includes the title
  • replace its contents with the html header with the text (the first descendant of this block)
 String html = "<HTML xmlns:OG=\"http://opengraphprotocol.org/schema/\" xmlns:FB=\"http://www.facebook.com/2008/fbml\">\n" + " <style type=\"text/css\"></style>\n" + " <BODY>\n" + " <DIV class=\"block0\">\n" + " <DIV class=\"pad0\">\n" + " <DIV class=\"fblock\">\n" + " <DIV class=\"block61\">\n" + " <DIV class=\"rpad\">\n" + " <H1 class=\"title\">Во Франции по подозрению в планировании теракта задержали двух девушек</H1>\n" + " <SPAN class=\"dt2\">Понедельник, 26 сентября 2016, 16:08</SPAN>\n" + " <DIV class=\"text\">\n" + " <P>Во французском городе Ницца по подозрению в планировании теракта были задержаны двое девушек.</P>\n" + " <P>Об этом сообщает <A href=\"https://www.afp.com\">AFP</A>.</P>\n" + " <P>Девушки в возрасте 17 и 18 лет подозреваются в планировании террористического нападения под руководством французского джихадиста Рашида Кассима.</P>\n" + " <P>Подростки рассказали следователям, что они планировали нападение под влиянием Рашида Кассима, который сейчас находится в Сирии или Ираке, на территории, которая контролируется террористической организацией &quot;Исламское государство&quot;.</P>\n" + " <P>Рашид Кассим, по мнению следователей, играет роль подстрекателя или спонсора, фактически призывая потенциальных террористов к совершению джихада во Франции.</P>\n" + " <P>Стоит добавить, что во время обыска в помещениях, которые принадлежат задержанными, стражи порядка не нашли оружия.</P>\n" + " <P>Издание отмечает, что девушки живут в том же районе, что и <A href=\"/rus/news/2016/07/15/7052184/\">Мохамед Лахуайедж-Бухлель, убивший 86 человек</A> в Ницце 14 июля.</P>\n" + " <P>Напомним, недавно французская <A href=\"/rus/news/2016/09/14/7054550/\">полиция задержала подростка</A>, подозреваемого в подготовке теракта в Париже.</P>\n" + " </DIV>\n" + " <DIV class=\"btit4\"><SPAN>ЧИТАЙ ТАКЖЕ</SPAN></DIV>\n" + " </DIV>\n" + " </DIV>\n" + " </DIV>\n" + " </DIV>\n" + " </DIV>\n" + " <DIV class=\"block0\">\n" + " <DIV class=\"pad0\">\n" + " <DIV class=\"fblock\">\n" + " <DIV class=\"block61\">\n" + " <DIV class=\"rpad\">\n" + " <H1 class=\"title\">Во Фsdfsdfsfх девушек</H1>\n" + " <SPAN class=\"dt2\">Понедельник, 26 сентября 2016, 16:08</SPAN>\n" + " <DIV class=\"btit4\"><SPAN>ЧИТАЙ ТАКЖЕ</SPAN></DIV>\n" + " </DIV>\n" + " </DIV>\n" + " </DIV>\n" + " </DIV>\n" + " </DIV>\n" + " </BODY>\n" + "</HTML>"; // загрузка html Document document = Jsoup.parse(html); // берем все элементы в который входит title Elements els = document.select(".rpad"); // пробегаясь по всем ним, меняем внутри html // child(0) - как раз html заголовка for (Element el : els) { el.html(el.child(0).toString()); } System.out.println(document); 

This code will eventually output

 <html xmlns:og="http://opengraphprotocol.org/schema/" xmlns:fb="http://www.facebook.com/2008/fbml"> <head> <style type="text/css"></style> </head> <body> <div class="block0"> <div class="pad0"> <div class="fblock"> <div class="block61"> <div class="rpad"> <h1 class="title">Во Франции по подозрению в планировании теракта задержали двух девушек</h1> </div> </div> </div> </div> </div> <div class="block0"> <div class="pad0"> <div class="fblock"> <div class="block61"> <div class="rpad"> <h1 class="title">Во Фsdfsdfsfх девушек</h1> </div> </div> </div> </div> </div> </body> </html> 

And without knowledge, the selection criterion with constantly different html, constantly different tags for a header with constantly different nesting headings with constantly different classes (or maybe lack thereof) of a tag with a header and generally any specific search criteria - you can only do using artificial intelligence

  • Thank. I will try to limit the number of sites that will parse and build on this already. - drugs_and_code
  • @ TolikBuguera just need to isolate a common feature of all of them, and then, perhaps, it will be possible to make some kind of algorithm for all of them - Alexey Shimansky