【问题标题】:Android: Extracting the text between two HTML tagsAndroid:提取两个 HTML 标签之间的文本
【发布时间】:2012-01-03 09:51:09
【问题描述】:

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

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

我在Java 中使用(swiki\.2\.1\\\")(.*)(\/div) 模式完成了这项工作,并从组$2 中获取了我想要的字符串。但是,这在android中不起作用。当我去打印 $2 的内容时,什么都没有出现,因为匹配失败。

有没有人在 android 中使用正则表达式时遇到过类似的问题,或者是否有更好的方法(非正则表达式)首先解析 HTML 页面。同样,这在标准的 java 测试程序中运行良好。任何帮助将不胜感激!

【问题讨论】:

  • jsoup.org 应该有 android 版本...关于您的错误/匹配失败...也许在设备上您正在加载本网站的移动版本...
  • 这是一个很好的观点。但是,我刚刚检查了 HTML,而我在网站的移动版本中寻找的是相同的。我现在看看那个链接,稍后再回复。谢谢

标签: java android html regex parsing


【解决方案1】:

对于 HTML-parsing-stuff,我总是使用 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;
    }

只需根据您的需要对其进行编辑。 :-)

【讨论】:

  • 如果你想从一个标签中获取一个文本值,比如你的例子:
    我需要的文本
    你需要检查一个 ContentNode并通过 content.getContent().toString(); 获取文本值;
猜你喜欢
  • 2011-12-31
  • 1970-01-01
  • 1970-01-01
  • 2011-11-09
  • 1970-01-01
  • 2016-09-10
  • 2018-03-16
  • 1970-01-01
  • 2016-06-22
相关资源
最近更新 更多