Android:从网页解析HTML

5
3个回答

9

Jsoup非常擅长从Android应用程序中解析简单的HTML:

http://jsoup.org/

要获取页面,只需执行以下操作:

URL url = new URL("http://upcdata.info/upc/7310870008741");
Document document = Jsoup.parse(url, 5000);

然后,您可以从文档(Document)中解析出您需要的任何内容。查看此链接以了解如何提取页面部分的简要说明: http://jsoup.org/cookbook/extracting-data/dom-navigation

2

如果您想从URL读取到一个字符串中:

StringBuffer myString = new StringBuffer();
try {
    String thisLine;
    URL u = new URL("http://www.google.com");
    DataInputStream theHTML = new DataInputStream(u.openStream());
    while ((thisLine = theHTML.readLine()) != null) {
        myString.append(thisLine);
    } 
} catch (MalformedURLException e) {

} catch (IOException e) {

}

// call toString() on myString to get the contents of the file your URL is
// pointing to.

这将为您提供一个包含HTML标记的普通字符串。

1
String tmpHtml = "<html>a whole bunch of html stuff</html>"; 
String htmlTextStr = Html.fromHtml(tmpHtml).toString(); 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接