首页 / HTML / jsoup解析Html
jsoup解析Html
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了jsoup解析Html,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2563字,纯文字阅读大概需要4分钟。
内容图文
其中获取html代码,可以使用如下代码实现:
- public String getHtmlString(String urlString) {
- try {
- URL url = new URL(urlString);
- URLConnection ucon = url.openConnection();
- InputStream instr = ucon.getInputStream();
- BufferedInputStream bis = new BufferedInputStream(instr);
- ByteArrayBuffer baf = new ByteArrayBuffer(500);
- int current = 0;
- while ((current = bis.read()) != -1) {
- baf.append((byte) current);
- }
- return EncodingUtils.getString(baf.toByteArray(), "gbk");
- } catch (Exception e) {
- return "";
- }
- }
传入一个网页链接,将返回此链接的html代码(String)。
然后就是解析此html代码了。经过google,发现了java的一个很好用的解析html的库,Jsoup:http://jsoup.org/
很容易使用,方法类似javascript和JQuery。只需先构建一个Jsoup的Document对象,然后就可以像使用js一个解析html了
- String htmlString = getHtmlString( "http://www.cnbeta.com" );
- Document document = Jsoup.parse(htmlString);
- String title = document.head().getElementsByTag( "title" ).text();
另外构建Document的时候也可以直接使用URL,像这样:
- Document doc = Jsoup.parse( new URL( "http://www.cnbeta.com" ), 5000 );
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
}));
}
原文:http://blog.csdn.net/chenaini119/article/details/45331989
内容总结
以上是互联网集市为您收集整理的jsoup解析Html全部内容,希望文章能够帮你解决jsoup解析Html所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。