百度百科搜索某个词条时其url格式为 https://baike.baidu.com/item/XXX/.+
而 https://baike.baidu.com/item/XXX 就可以得到我们想要网页,
通过审查元素发现简介在这个位置
用document.select("div[class=\"lemma-summary\"]");的得到所有此标签的Elements
关键代码
String url = "https://baike.baidu.com/item/";
public void getSummary(View view) {//onClick生成的方法,监听一个Button if(!isNetworkAvailable(MainActivity.this)){ Toast.makeText(this,"网络不可用",Toast.LENGTH_SHORT).show(); return; } if(et_main_content.getText().toString().equals("")){ Toast.makeText(this,"请输入内容",Toast.LENGTH_SHORT).show(); }else{ new Thread(new Runnable() { @Override public void run() { OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder() .url(url + et_main_content.getText()) .build(); try { Response response = client.newCall(request).execute(); String html = response.body().string(); Document document = Jsoup.parse(html); Elements links = document.select("div[class=\"lemma-summary\"]"); String result = ""; for (Element link : links) { result += link.text(); } if(result == ""){ showResult("未查到"); return; } Log.e("TAG",result); showResult(result); } catch (IOException e) { e.printStackTrace(); } } }).start(); } } private void showResult(final String result){ runOnUiThread(new Runnable() { @Override public void run() { tv_main_html.setText(result);//在TextView中显示 } }); } public static boolean isNetworkAvailable(Context context) {//检查网络是否可用 ConnectivityManager mgr = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo[] info = mgr.getAllNetworkInfo(); if (info != null) { for (int i = 0; i < info.length; i++) { if (info[i].getState() == NetworkInfo.State.CONNECTED) { return true; } } } return false; }
注意:
添加android.permission.INTERNET 和 android.permission.ACCESS_NETWORK_STATE权限
必须在UI线程中更新界面
OkHttp和jsoup都是第三方jar包,先要导好jar包