Android:如何解析HTML页面?
我是android编程新手。我想知道如何解析网页并将特定内容提取到ListView中。最简单和最好的方法是什么?有人能用下面给出的例子给我看看吗 URL=“Something.com” 我想提取每个城市的名称和href链接Android:如何解析HTML页面?,android,sdk,html-parsing,android-webview,Android,Sdk,Html Parsing,Android Webview,我是android编程新手。我想知道如何解析网页并将特定内容提取到ListView中。最简单和最好的方法是什么?有人能用下面给出的例子给我看看吗 URL=“Something.com” 我想提取每个城市的名称和href链接 谢谢你们,很抱歉问了这个基本问题 使用类似的方法获取html内容 然后使用类似 提取URL 然后 :matches(regex):查找其文本与指定正则表达式匹配的元素;e、 g.分区:匹配((?i)登录) 对要查找的url执行正则表达式 我不确定这是否是您想要的
谢谢你们,很抱歉问了这个基本问题 使用类似的方法获取html内容 然后使用类似 提取URL 然后 :matches(regex):查找其文本与指定正则表达式匹配的元素;e、 g.分区:匹配((?i)登录) 对要查找的url执行正则表达式 我不确定这是否是您想要的。使用类似的方式获取html内容 然后使用类似 提取URL 然后 :matches(regex):查找其文本与指定正则表达式匹配的元素;e、 g.分区:匹配((?i)登录) 对要查找的url执行正则表达式
我不确定这是否是您想要的。查看下面的代码,如果您有任何疑问,请告诉我,并查看此链接,它可能会对您有所帮助
公共类MainActivity扩展活动{
列表视图;
@凌驾
创建时的公共void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//指向JSON数据的URL
字符串strUrl=“ur url/国家”;
//创建新的非ui线程任务以下载json数据
DownloadTask DownloadTask=新的DownloadTask();
//开始下载过程
下载任务。执行(strUrl);
//获取对活动“”的ListView的引用
mListView=(ListView)findViewById(R.id.lv_国家);
}
/**从url下载json数据的方法*/
私有字符串下载URL(字符串strUrl)引发IOException{
字符串数据=”;
InputStream iStream=null;
试一试{
URL=新URL(strUrl);
//创建http连接以与url通信
HttpURLConnection urlConnection=(HttpURLConnection)url.openConnection();
//连接到url
urlConnection.connect();
//从url读取数据
iStream=urlConnection.getInputStream();
BufferedReader br=新的BufferedReader(新的InputStreamReader(iStream));
StringBuffer sb=新的StringBuffer();
字符串行=”;
而((line=br.readLine())!=null){
某人附加(行);
}
data=sb.toString();
br.close();
}捕获(例外e){
Log.d(“下载url时出现异常”,例如toString());
}最后{
iStream.close();
}
返回数据;
}
/**AsyncTask下载json数据*/
私有类DownloadTask扩展了AsyncTask{
字符串数据=null;
@凌驾
受保护的字符串doInBackground(字符串…url){
试一试{
数据=下载url(url[0]);
}捕获(例外e){
Log.d(“后台任务”,例如toString());
}
返回数据;
}
@凌驾
受保护的void onPostExecute(字符串结果){
//xml数据的解析在非ui线程中完成
ListViewLoaderTask ListViewLoaderTask=新建ListViewLoaderTask();
//开始解析xml数据
listViewLoaderTask.execute(结果);
}
}
/**AsyncTask解析json数据并加载ListView*/
私有类ListViewLoaderTask扩展异步任务{
JSONObject jObject;
//在非ui线程中解析xml数据
@凌驾
受保护的SimpleAdapter doInBackground(字符串…strJson){
试一试{
jObject=新的JSONObject(strJson[0]);
CountryJSONParser CountryJSONParser=新的CountryJSONParser();
parse(jObject);
}捕获(例外e){
d(“JSON例外1”,例如toString());
}
//实例化json解析器类
CountryJSONParser CountryJSONParser=新的CountryJSONParser();
//用于存储已解析的国家/地区列表的列表对象
列表国家=空;
试一试{
//将解析后的数据作为列表构造获取
countries=countryJsonParser.parse(jObject);
}捕获(例外e){
Log.d(“异常”,例如toString());
}
//Hashmap中使用的键
字符串[]from={“国家”
//listview\u布局中的视图ID
int[]to={R.id.tv_country};
//实例化适配器以存储每个项
//R.layout.listview\u布局定义每个项目的布局
SimpleAdapter=new SimpleAdapter(getBaseContext(),国家/地区,R.layout.lv_布局,从,到);
返回适配器;
}
/**由Android在“doInBackground”上调用*/
@凌驾
受保护的void onPostExecute(SimpleAdapter适配器){
//设置listview的适配器
mListView.setAdapter(适配器);
对于(int i=0;i请查看下面的代码,如果您有任何疑问,请告诉我,并查看此链接,它可能会对您有所帮助
公共类MainActivity扩展活动{
列表视图;
@凌驾
创建时的公共void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//指向JSON数据的URL
字符串strUrl=“ur url/国家”;
//创建新的非ui线程任务以下载json数据
DownloadTask DownloadTask=n
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;
}
}
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 ;)
}
}