如何使用jsoup获取div标签

时间:2017-11-26 11:40:18

标签: android jsoup

我想从网站上获取一些数据。它看起来像

<div id="1" class="tms"> 
    <div class="point">
     TINAZTEPE
    </div> 
    <div class="days"> 
     <div class="day">
      Hafta İçi
     </div> 
     <div>
      "06:45" 
      <i class="fa fa-wheelchair"></i>
     </div> 
     <div>
      "07:00" 
      <i class="fa fa-wheelchair"></i>
     </div> 
     <div>
      "07:15" 
      <i class="fa fa-wheelchair"></i>
     </div> 
     <div>
      "07:25" 
      <i class="fa fa-wheelchair"></i>
     </div> 
     <div>
      "07:30" 
      <i class="fa fa-wheelchair"></i>
     </div> 
     <div>
      "07:45" 
      <i class="fa fa-wheelchair"></i>
     </div> 

我只需要在div标签中获取时间值。那是我的Java代码

 ArrayList<String> info=new ArrayList<String>();
    try
    {
        Document document = Jsoup.connect("https://nevakit.com/otobus/izmir/412").get();
        Elements broadcasts = document.select("div[id=1]");

        for (Element element : broadcasts) {

            info.add(element.getElementsByTag("div").text());

        }

        String total=null;
        for(String temp:info)
        {
            total+=temp;
        }

        txtView.setText(total);

    }catch(Exception e)
    {
        e.printStackTrace();
    }

它不会在logcat上给出任何错误

  

“D / NetworkSecurityConfig:未指定网络安全配置,使用平台默认值”

我看到也许这可以帮助你解决问题。提前感谢您,我们将不胜感激。

1 个答案:

答案 0 :(得分:0)

您需要使用AsynTask在代码

下面执行此操作
 class PerformTask extends AsyncTask<Void,Void,Void>{
        ArrayList<String> info=new ArrayList<String>();
        @Override
        protected Void doInBackground(Void... voids) {
            try
            {
                Document document = Jsoup.connect("https://nevakit.com/otobus/izmir/412").get();
                Elements broadcasts = document.select("div[id=1]");

                for (Element element : broadcasts) {

                    info.add(element.getElementsByTag("div").text());

                }


            }catch(Exception e)
            {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
            String total=null;
             for(String temp:info)
                {
                    total+=temp;
                }
            txtView.setText(total);
        }
    }

从OnCrate中调用它,如下所示

new PerformTask().execute();