国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 系統 > Android > 正文

android Jsoup獲取網站內容 android獲取新聞標題實例

2019-12-12 03:13:48
字體:
來源:轉載
供稿:網友

近期做簡單的新聞客戶端界面使用到了Jsoup獲取,使用起來特別方便,這也是被我一個學長稱為學android網絡必學的一個東西,在此也是分享一下自己近期所學。

首先還是給出效果:

上面是通過textview顯示的一個從網站上獲取的所有內容的顯示,下面是通過listview顯示一下獲取的新聞的標題,如此顯示比較便于理解。

MainActivity:

import android.app.Activity; import android.content.Intent; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.text.method.ScrollingMovementMethod; import android.util.Log; import android.view.Menu; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.TextView;  import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.util.EntityUtils; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements;  import java.util.ArrayList; import java.util.List;  @SuppressWarnings("unused") public class MainActivity extends Activity {   private TextView TV_HTMLCode;   //此處搞一個TextView主要來顯示News列表里面存儲的內容,僅僅便于分析和理解    private String URL_EOL = "http://www.cnwust.com/newsList/1_1",       TAG = "ATAG";   //這是索要獲取內容的網址    private List<News> NewsList;   //自定義的News的類,用于存放索要獲取新聞的目錄、時間以及點擊后顯示的網址    private ListView LV_Result;   private ArrayAdapter<String> LV_Adapter;    @Override   protected void onCreate(Bundle savedInstanceState) {     super.onCreate(savedInstanceState);     setContentView(R.layout.activity_main);     LV_Result = (ListView) findViewById(R.id.LV_Result);     TV_HTMLCode = (TextView) findViewById(R.id.TV_HTMLCode);     TV_HTMLCode.setMovementMethod(ScrollingMovementMethod.getInstance());      ConnectTask C1 = new ConnectTask();     C1.execute();    }    @Override   public boolean onCreateOptionsMenu(Menu menu) {     getMenuInflater().inflate(R.menu.menu_main, menu);     return true;   }    public class ConnectTask extends AsyncTask<Void, Void, String> {      @Override     protected String doInBackground(Void... params) {       String result = ConnectEOL();       return result;     }      @Override     protected void onPostExecute(String result) {       // TV_HTMLCode.setText(result);       NewsList = getNews(result);       List<String> NewsTitles = new ArrayList<String>();       for (News news : NewsList) {         TV_HTMLCode.append(news.getNewsTitle() + "/n");         TV_HTMLCode.append(news.getNewsTime() + "/n");         TV_HTMLCode.append(news.getNewsUrl() + "/n");         NewsTitles.add(news.getNewsTitle());       }     /* 為ListView添加適配器 */        LV_Adapter = new ArrayAdapter<String>(MainActivity.this,           android.R.layout.simple_list_item_1, NewsTitles);       LV_Result.setAdapter(LV_Adapter);      /* 為ListView添加點擊打開對應網頁功能 */       LV_Result.setOnItemClickListener(new OnItemClickListener() {          @Override         public void onItemClick(AdapterView<?> arg0, View arg1,                     int arg2, long arg3) {           final Uri uri = Uri.parse(NewsList.get(arg2).getNewsUrl());           final Intent it = new Intent(Intent.ACTION_VIEW, uri);           startActivity(it);         }        });       //此處為了方便就點擊就直接調用設備默認瀏覽器打開網址        super.onPostExecute(result);       }    }    /* 連接EOL的方法 返回整個網頁經過截取之后的的源代碼 */   public String ConnectEOL() {     String result = "";     try {       HttpClient httpclient = new DefaultHttpClient();       HttpPost httppost = new HttpPost(URL_EOL);       HttpResponse response = httpclient.execute(httppost);       String Res = EntityUtils.toString(response.getEntity(), "UTF-8");        int st = Res.indexOf("<div id=/"result/">");       int ed = Res.indexOf("<div id=/"pager/">");       //這邊算是最重要的部分,代碼獲取的便是這兩段之間的部分。        String content = Res.substring(st, ed);       st = content.indexOf("<ul>") + 4;       ed = content.indexOf("</ul>");       content = content.substring(st, ed);       result = content;     } catch (Exception e) {       Log.d(TAG, e.toString());     }     return result;   }    /* 對源代碼進行解析截取的方法 返回一個News數組 */   public List<News> getNews(String HTMLCode) {     List<News> newsList = new ArrayList<News>();     Document doc = Jsoup.parse(HTMLCode);     Log.d(TAG, "解析html中");     Elements lis = doc.getElementsByTag("li");     Log.d(TAG, "lis的size " + lis.size());     for (Element li : lis) {       String newstime = li.getElementsByTag("span").text();       String newstitle = li.getElementsByTag("a").text();       String newsurl = li.getElementsByTag("a").attr("href");       //這三段算是Jsoup從html中獲取內容的關鍵了,很容易理解。        newsurl = newsurl.replace("/news", "http://www.cnwust.com/news");       //直接從html的代碼中獲取的URL是相對路徑,此處使用replace改為絕對路徑        Log.d(TAG, newstime);       Log.d(TAG, newstitle);       Log.d(TAG, newsurl);        News newst = new News();       newst.setNewsTime(newstime);       newst.setNewsTitle(newstitle);       newst.setNewsUrl(newsurl);       newsList.add(newst);     }     return newsList;   } } 

News:

public class News {   private String newsTime;   private String newsUrl;   private String newsTitle;    public News() {    }    public News(String newsTitle, String newsTime, String newsUrl) {     this.newsTime = newsTime;     this.newsUrl = newsUrl;     this.newsTitle = newsTitle;   }    public String getNewsTime() {     return newsTime;   }    public void setNewsTime(String newsTime) {     this.newsTime = newsTime;   }    public String getNewsUrl() {     return newsUrl;   }    public void setNewsUrl(String newsUrl) {     this.newsUrl = newsUrl;   }    public String getNewsTitle() {     return newsTitle;   }    public void setNewsTitle(String newsTitle) {     this.newsTitle = newsTitle;   }  } 

activity_main:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"   xmlns:tools="http://schemas.android.com/tools"   android:layout_width="match_parent"   android:layout_height="match_parent"   android:paddingBottom="@dimen/activity_vertical_margin"   android:paddingLeft="@dimen/activity_horizontal_margin"   android:paddingRight="@dimen/activity_horizontal_margin"   android:paddingTop="@dimen/activity_vertical_margin"   tools:context=".NewsList" >    <TextView     android:id="@+id/TV_HTMLCode"     android:layout_width="match_parent"     android:layout_height="150dp"     android:layout_above="@+id/LV_Result"     android:layout_alignParentTop="true"     android:layout_centerHorizontal="true"     android:scrollbars="vertical" />    <ListView     android:id="@+id/LV_Result"     android:layout_width="match_parent"     android:layout_height="230dp"     android:layout_alignLeft="@+id/TV_HTMLCode"     android:layout_alignParentBottom="true" >   </ListView>  </RelativeLayout> 

此處對html代碼的解析可能部分新手還是不太清楚,在此也是建議使用chrome瀏覽器,可以直接查看網站的源碼。(有部分加密的網站看不到)下面看一下具體使用的截圖:

1、首先先要打開到你要獲取內容的網站


2、右擊你要獲取的內容,并選擇  審查元素。


3、使用Jsoup解析html代碼。


最后是附上源碼下載地址

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 望奎县| 塔城市| 遵义市| 奉新县| 山阳县| 上犹县| 宁乡县| 伊宁县| 汨罗市| 玉田县| 三穗县| 田阳县| 赤城县| 定日县| 斗六市| 南涧| 佛学| 始兴县| 麦盖提县| 宜良县| 砀山县| 金堂县| 通海县| 五华县| 伊吾县| 德江县| 塔河县| 扬州市| 连城县| 苏尼特左旗| 兴国县| 南昌市| 同江市| 双峰县| 敦煌市| 南澳县| 济源市| 武城县| 历史| 临沧市| 连南|