近期做簡單的新聞用戶端界面使用到了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代碼。
最後是附上源碼下載下傳位址:http://download.csdn.net/detail/double2hao/9155293
本人部落格,android均為新手,聞過則喜,望各位前輩不吝指點批評。