android Jsoup獲取網(wǎng)站內(nèi)容 android獲取新聞標(biāo)題實(shí)例
近期做簡單的新聞客戶端界面使用到了Jsoup獲取,使用起來特別方便,這也是被我一個(gè)學(xué)長稱為學(xué)android網(wǎng)絡(luò)必學(xué)的一個(gè)東西,在此也是分享一下自己近期所學(xué)。
首先還是給出效果:

上面是通過textview顯示的一個(gè)從網(wǎng)站上獲取的所有內(nèi)容的顯示,下面是通過listview顯示一下獲取的新聞的標(biāo)題,如此顯示比較便于理解。
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;
//此處搞一個(gè)TextView主要來顯示News列表里面存儲(chǔ)的內(nèi)容,僅僅便于分析和理解
private String URL_EOL = "http://www.cnwust.com/newsList/1_1",
TAG = "ATAG";
//這是索要獲取內(nèi)容的網(wǎng)址
private List<News> NewsList;
//自定義的News的類,用于存放索要獲取新聞的目錄、時(shí)間以及點(diǎn)擊后顯示的網(wǎng)址
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添加點(diǎn)擊打開對應(yīng)網(wǎng)頁功能 */
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);
}
});
//此處為了方便就點(diǎn)擊就直接調(diào)用設(shè)備默認(rèn)瀏覽器打開網(wǎng)址
super.onPostExecute(result);
}
}
/* 連接EOL的方法 返回整個(gè)網(wǎng)頁經(jīng)過截取之后的的源代碼 */
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;
}
/* 對源代碼進(jìn)行解析截取的方法 返回一個(gè)News數(shù)組 */
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中獲取內(nèi)容的關(guān)鍵了,很容易理解。
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瀏覽器,可以直接查看網(wǎng)站的源碼。(有部分加密的網(wǎng)站看不到)下面看一下具體使用的截圖:
1、首先先要打開到你要獲取內(nèi)容的網(wǎng)站

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

3、使用Jsoup解析html代碼。

最后是附上源碼下載地址
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Android LinearLayout實(shí)現(xiàn)自動(dòng)換行
這篇文章主要為大家詳細(xì)介紹了Android LinearLayout實(shí)現(xiàn)自動(dòng)換行,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-08-08
Android中多個(gè)EditText輸入效果的解決方式
這篇文章主要給大家介紹了關(guān)于Android中多個(gè)EditText輸入效果的解決方式,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-01-01
Android自定義控件EditText實(shí)現(xiàn)清除和抖動(dòng)功能
這篇文章主要為大家詳細(xì)介紹了Android自定義控件EditText實(shí)現(xiàn)清除和抖動(dòng)功能,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-12-12
Android序列化接口Parcelable與Serializable接口對比
我們使用 Intent 傳遞數(shù)據(jù)的時(shí)候,putExtra() 所支持的數(shù)據(jù)類型事有限的,當(dāng)需要傳遞自定義對象的時(shí)候就需要序列化。Serializable更簡單但是會(huì)把整個(gè)對象進(jìn)行序列化因此效率比Parcelable低一些2023-02-02
android圖片文件的路徑地址與Uri的相互轉(zhuǎn)換方法
下面小編就為大家?guī)硪黄猘ndroid圖片文件的路徑地址與Uri的相互轉(zhuǎn)換方法。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-04-04
android如何添加桌面圖標(biāo)和卸載程序后自動(dòng)刪除圖標(biāo)
android如何添加桌面圖標(biāo)和卸載程序后自動(dòng)刪除桌面圖標(biāo),這是一個(gè)應(yīng)用的安裝與卸載過程對桌面圖標(biāo)的操作,下面與大家分享下具體是如何實(shí)現(xiàn)的,感興趣的朋友可以參考下哈2013-06-06

