如何使用JSOUP在Android中解析嵌套div?

时间:2017-08-30 19:36:01

标签: android jsoup

我有以下HTML代码:

  <div id="app"> 
<div data-reactroot id="timetable-content-holder">
<div class="top-bar"> ... </div> 
<h2>I need it </h2> 
<div class="timetable-holder gr-holder"> 
<div class="timetable-day gr"> 
<div class = "timetable-day-title"> Daily </dv> 
</div> 
</div> 
</div> 
     </div> 

我需要在h2内解析timetable-day-title和文字。我不能写select方法。这是我的考验:

Elements elements = document.select("div#app > div#timetable-content-holder > h2");

elements大小为零。在我的案例中如何编写文档的选择方法?

1 个答案:

答案 0 :(得分:2)

您可以按逗号分隔符选择标记

 String html =" <div id=\"app\"> \n" +
                 "<div data-reactroot id=\"timetable-content-holder\">\n" +
                 "<div class=\"top-bar\"> ... </div> \n" +
                 "<h2>I need it </h2> \n" +
                 "<div class=\"timetable-holder gr-holder\"> \n" +
                 "<div class=\"timetable-day gr\"> \n" +
                 "<div class = \"timetable-day-title\"> Daily </dv> \n" +
                 "</div> \n" +
                 "</div> \n" +
                 "</div> \n" +
                 "     </div> ";

        Document document = Jsoup.parse(html);
        Elements elements = document.select("#app #timetable-content-holder h2,.timetable-day-title ");
        for (Element element:elements){
            System.out.println(element.text());
        }

<强>更新 尝试使用此代码从url调用

Document doc = Jsoup.connect("http://YourURL.com").get();

输出:

I need it
Daily