Android:提取两个HTML标签之间的文本



我需要提取两个HTML标记之间的文本并将其存储在字符串中。我要解析的HTML示例如下:

<div id="swiki.2.1"> THE TEXT I NEED </div>

我已经在Java中使用模式(swiki.2.1\")(.*)(/div)并从组$2中获得我想要的字符串。然而,这将不能在android中工作。当我去打印$2的内容时,什么也没有出现,因为匹配失败。

有没有人在android中使用regex有类似的问题,或者有更好的方法(非regex)首先解析HTML页面。同样,这在标准java测试程序中工作得很好。任何帮助将非常感激!

对于html解析的东西,我总是使用HtmlCleaner: http://htmlcleaner.sourceforge.net/

很棒的库,可以很好地使用Xpath,当然还有Android。: -)

这展示了如何从URL下载XML并解析它以从XML属性(也在文档中显示)获得特定值:

public static String snapFromHtmlWithCookies(Context context, String xPath, String attrToSnap, String urlString,
                    String cookies) throws IOException, XPatherException {
            String snap = "";
            // create an instance of HtmlCleaner
            HtmlCleaner cleaner = new HtmlCleaner();
            // take default cleaner properties
            CleanerProperties props = cleaner.getProperties();
            props.setAllowHtmlInsideAttributes(true);
            props.setAllowMultiWordAttributes(true);
            props.setRecognizeUnicodeChars(true);
            props.setOmitComments(true);
            URL url = new URL(urlString);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            // optional cookies
            connection.setRequestProperty(context.getString(R.string.cookie_prefix), cookies);
            connection.connect();
            // use the cleaner to "clean" the HTML and return it as a TagNode object
            TagNode root = cleaner.clean(new InputStreamReader(connection.getInputStream()));
            Object[] foundNodes = root.evaluateXPath(xPath);
            if (foundNodes.length > 0) {
                    TagNode foundNode = (TagNode) foundNodes[0];
                    snap = foundNode.getAttributeByName(attrToSnap);
            }
            return snap;
    }

根据你的需要编辑它。: -)

最新更新