标签:html android jsoup
何使用Jsoup这个库来解析我们的网页,并且如何对我们想解析的网页进行分析。
其中获取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);
比如要获取cnbeta的html的title,只需:
-
String title = document.head().getElementsByTag("title").text();
另外构建Document的时候也可以直接使用URL,像这样:
-
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