我新來的android編程。我想知道如何解析網頁並將特定內容提取到ListView中。什麼是最簡單和最好的方式來做到這一點?有人能給我看一個使用下面給出的例子嗎?Android:我如何解析HTML頁面?
URL =「Something.com」。
我想提取每個城市的名稱和href鏈接。
ann arborbattle creek
central michigan
detroit metro
flint
grand rapids
謝謝你們在百忙之中提出這個基本問題。
我新來的android編程。我想知道如何解析網頁並將特定內容提取到ListView中。什麼是最簡單和最好的方式來做到這一點?有人能給我看一個使用下面給出的例子嗎?Android:我如何解析HTML頁面?
URL =「Something.com」。
我想提取每個城市的名稱和href鏈接。
ann arbor謝謝你們在百忙之中提出這個基本問題。
看看下面的代碼,讓我知道,如果您有任何疑問,看看這個鏈接,它可以幫助你
public class MainActivity extends Activity {
ListView mListView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// URL to the JSON data
String strUrl = "ur url/countries";
// Creating a new non-ui thread task to download json data
DownloadTask downloadTask = new DownloadTask();
// Starting the download process
downloadTask.execute(strUrl);
// Getting a reference to ListView of activity_main
mListView = (ListView) findViewById(R.id.lv_countries);
}
/** A method to download json data from url */
private String downloadUrl(String strUrl) throws IOException{
String data = "";
InputStream iStream = null;
try{
URL url = new URL(strUrl);
// Creating an http connection to communicate with url
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
// Connecting to url
urlConnection.connect();
// Reading data from url
iStream = urlConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
StringBuffer sb = new StringBuffer();
String line = "";
while((line = br.readLine()) != null){
sb.append(line);
}
data = sb.toString();
br.close();
}catch(Exception e){
Log.d("Exception while downloading url", e.toString());
}finally{
iStream.close();
}
return data;
}
/** AsyncTask to download json data */
private class DownloadTask extends AsyncTask<String, Integer, String>{
String data = null;
@Override
protected String doInBackground(String... url) {
try{
data = downloadUrl(url[0]);
}catch(Exception e){
Log.d("Background Task",e.toString());
}
return data;
}
@Override
protected void onPostExecute(String result) {
// The parsing of the xml data is done in a non-ui thread
ListViewLoaderTask listViewLoaderTask = new ListViewLoaderTask();
// Start parsing xml data
listViewLoaderTask.execute(result);
}
}
/** AsyncTask to parse json data and load ListView */
private class ListViewLoaderTask extends AsyncTask<String, Void, SimpleAdapter>{
JSONObject jObject;
// Doing the parsing of xml data in a non-ui thread
@Override
protected SimpleAdapter doInBackground(String... strJson) {
try{
jObject = new JSONObject(strJson[0]);
CountryJSONParser countryJsonParser = new CountryJSONParser();
countryJsonParser.parse(jObject);
}catch(Exception e){
Log.d("JSON Exception1",e.toString());
}
// Instantiating json parser class
CountryJSONParser countryJsonParser = new CountryJSONParser();
// A list object to store the parsed countries list
List<HashMap<String, Object>> countries = null;
try{
// Getting the parsed data as a List construct
countries = countryJsonParser.parse(jObject);
}catch(Exception e){
Log.d("Exception",e.toString());
}
// Keys used in Hashmap
String[] from = { "country"
// Ids of views in listview_layout
int[] to = { R.id.tv_country};
// Instantiating an adapter to store each items
// R.layout.listview_layout defines the layout of each item
SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), countries, R.layout.lv_layout, from, to);
return adapter;
}
/** Invoked by the Android on "doInBackground" is executed */
@Override
protected void onPostExecute(SimpleAdapter adapter) {
// Setting adapter for the listview
mListView.setAdapter(adapter);
for(int i=0;i<adapter.getCount();i++){
HashMap<String, Object> hm = (HashMap<String, Object>) adapter.getItem(i);
HashMap<String, Object> hmDownload = new HashMap<String, Object>();
hm.put("flag_path",imgUrl);
hm.put("position", i);
}
}
}
@Override
protected void onPostExecute(HashMap<String, Object> result) {
// Getting the path to the downloaded image
String path = (String) result.get("flag");
// Getting the position of the downloaded image
int position = (Integer) result.get("position");
// Getting adapter of the listview
SimpleAdapter adapter = (SimpleAdapter) mListView.getAdapter();
// Getting the hashmap object at the specified position of the listview
HashMap<String, Object> hm = (HashMap<String, Object>) adapter.getItem(position);
// Overwriting the existing path in the adapter
hm.put("flag",path);
// Noticing listview about the dataset changes
adapter.notifyDataSetChanged();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
使用類似http://jsoup.org/來獲取html內容。
然後使用類似
http://jsoup.org/cookbook/extracting-data/selector-syntax
提取的URL。
然後
:匹配(正則表達式):發現的元素其文字的指定正則表達式匹配;例如div:匹配((?i)登錄)
爲您正在尋找的網址做一個正則表達式。
我不確定這是你想要的。
我記得我這樣做一次,幸運的是我發現的代碼。 你只需要從你的活動 給這個Intentservice打個電話,你需要在頂部指定網站名稱(URL變量)
public class parser extends IntentService {
public String url="http://www.mywebsite.com";
@Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
// shutdown();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
return super.onStartCommand(intent, flags, startId);
}
private Timer t = new Timer();
byte[] buffer;
public timeCell() {
super("name");
// TODO Auto-generated constructor stub
}
@Override
protected void onHandleIntent(Intent arg0) {
// TODO Auto-generated method stub
t.schedule(new TimerTask(){
@Override
public void run() {
// TODO Auto-generated method stub
BufferedReader reader=null;
try {
reader = new BufferedReader(
new InputStreamReader(
new URL(url).openStream()));
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String line = null;
try {
line = reader.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.v("line was ", line); // printing is done here ;)
}
}
學習如何使用XML解析器。有很多可用的例子。 –
@AndroSelva我認爲他在談論HTML內容解析! –
是的,但他正在談論abt特定標籤解析。不會XML解析是更好的選擇? –