码迷,mamicode.com
首页 > Web开发 > 详细

jsoup解析Html

时间:2015-04-28 11:55:33      阅读:129      评论:0      收藏:0      [点我收藏+]

标签:html   android   jsoup   

何使用Jsoup这个库来解析我们的网页,并且如何对我们想解析的网页进行分析。
Jsoup这个库的下载地址:http://jsoup.org/download

Jsoup的资料比较少,可供参考的可到其官网进行学习这个库的使用:http://www.open-open.com/jsoup/
API查阅地址:http://jsoup.org/apidocs/


其中获取html代码,可以使用如下代码实现:

  1. public String getHtmlString(String urlString) {  
  2.     try {  
  3.         URL url = new URL(urlString);  
  4.         URLConnection ucon = url.openConnection();  
  5.         InputStream instr = ucon.getInputStream();  
  6.         BufferedInputStream bis = new BufferedInputStream(instr);  
  7.         ByteArrayBuffer baf = new ByteArrayBuffer(500);  
  8.         int current = 0;  
  9.         while ((current = bis.read()) != -1) {  
  10.             baf.append((byte) current);  
  11.         }  
  12.         return EncodingUtils.getString(baf.toByteArray(), "gbk");  
  13.     } catch (Exception e) {  
  14.         return "";  
  15.     }  
  16. }  

传入一个网页链接,将返回此链接的html代码(String)。


然后就是解析此html代码了。经过google,发现了java的一个很好用的解析html的库,Jsoup:http://jsoup.org/

很容易使用,方法类似javascript和JQuery。只需先构建一个Jsoup的Document对象,然后就可以像使用js一个解析html了

  1. String htmlString = getHtmlString("http://www.cnbeta.com");  
  2. Document document = Jsoup.parse(htmlString);  
比如要获取cnbeta的html的title,只需:
  1. String title = document.head().getElementsByTag("title").text();  

另外构建Document的时候也可以直接使用URL,像这样:

  1. Document doc = Jsoup.parse(new URL("http://www.cnbeta.com"), 5000);  
其中5000是连接网络的超时时间。

随便写一个代码
public class GetWebActivity extends Activity {


Document doc;
private TextView text;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);


text=(TextView)findViewById(R.id.text);

load();
}


protected void load() {

try {
doc = Jsoup.parse(new URL("http://www.cnbeta.com"), 5000);
} catch (MalformedURLException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
//String htmlString = getHtmlString("http://www.cnbeta.com");  //第二种
String title=doc.getElementsByTag("title").text().toString();
text.setText(title);
List<Map<String, String>> list = new ArrayList<Map<String, String>>();
Elements es = doc.getElementsByClass("sublist");
for (Element e : es) {
Map<String, String> map = new HashMap<String, String>();
map.put("title", e.getElementsByTag("a").text());
map.put("href", "http://www.cnbeta.com"
+ e.getElementsByTag("a").attr("href"));
list.add(map);
}

ListView listView = (ListView) findViewById(R.id.listView1);
listView.setAdapter(new SimpleAdapter(this, list, R.layout.item,
new String[] { "title","href" }, new int[] {
android.R.id.text1,android.R.id.text2
}));
}
你可以先简单就去去title 看看能不能解析,别的药解析参考api 就好

jsoup解析Html

标签:html   android   jsoup   

原文地址:http://blog.csdn.net/chenaini119/article/details/45331989

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!