本来想用 import org.jsoup.Jsoup;
或者 import org.htmlparser.Parser;
可是 android 不支持 sun 原生java字节码执行 ,而是自成一家.
因为 android 采用的是 Dalvik 虚拟机,而 htmlparser.jar 的编译是在传统 sun Java 虚拟机上完成编译的,所以将 htmlparser.jar 导入 Android 工程后并不能直接使用。
只能靠自己写了 ,例如: beanshell 抓取优快云极客头条内容
TestHtmlParser.bsh
import java.net.*;
import java.io.*;
import org.json.*;
String utf8(String str){
return new String(str.getBytes("8859_1"),"UTF-8");
}
String getText(String txt,char c, tag){
int begin = txt.indexOf(c);
if (begin > -1){
begin += 1;
end = txt.indexOf(tag,begin);
if (begin<end){
return txt.substring(begin,end);
} else {
return null;
}
} else {
return null;
}
}
getPage(String url){
String prefix = "<a href=";
String buf;
String line;
try {
Url = new URL(url);
conn = Url.openConnection();
ins = new DataInputStream(conn.getInputStream());
while((line= ins.readLine()) != null){
buf = line.trim();
if (buf.startsWith(prefix)){
String href = getText(buf,'"','"');
//print(href);
if (href != null && href.startsWith("http://")){
if (! href.startsWith("http://www.youkuaiyun.com")){
print(href);
print(utf8(getText(buf,'>',"</a>")));
}
}
}
}
ins.close();
} catch(e) {
print(e);
}
}
getPage("http://geek.youkuaiyun.com/new");
在android 4.2 上测试通过.