unj*_*nj2 25 html android web-scraping
我需要从Android中的非结构化网页中提取信息.我想要的信息嵌入在没有id的表中.
<table>
<tr><td>Description</td><td></td><td>I want this field next to the description cell</td></tr>
</table>
Run Code Online (Sandbox Code Playgroud)
我应该用吗?
或者有更快的方式来获取这些信息?
Jos*_*ger 47
我认为在这种情况下,寻找一种快速提取信息的方法是没有意义的,因为当您将答案与下载 HTML 所需的时间进行比较时,答案中已经建议的方法几乎没有任何性能差异.
因此,假设最快的意思是最方便,可读和可维护的代码,我建议您使用a DocumentBuilder
来解析相关的HTML并使用XPathExpression
s 提取数据:
Document doc = DocumentBuilderFactory.newInstance()
.newDocumentBuilder().parse(new InputSource(new StringReader(html)));
XPathExpression xpath = XPathFactory.newInstance()
.newXPath().compile("//td[text()=\"Description\"]/following-sibling::td[2]");
String result = (String) xpath.evaluate(doc, XPathConstants.STRING);
Run Code Online (Sandbox Code Playgroud)
如果您碰巧检索到无效的HTML,我建议隔离相关部分(例如使用substring(indexOf("<table")..
),并String
在解析之前根据需要更正剩余的HTML错误.如果这变得过于复杂(即非常糟糕的 HTML),那么就像其他答案中建议的那样采用hacky模式匹配方法.
备注
Bal*_*usC 19
在最快的方式将解析特定的个人信息.您似乎事先已经准确地了解了HTML结构.的BufferedReader
,String
和StringBuilder
方法应该足够了.这是一个启动示例,显示您自己问题的第一段:
public static void main(String... args) throws Exception {
URL url = new URL("http://stackoverflow.com/questions/2971155");
BufferedReader reader = null;
StringBuilder builder = new StringBuilder();
try {
reader = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8"));
for (String line; (line = reader.readLine()) != null;) {
builder.append(line.trim());
}
} finally {
if (reader != null) try { reader.close(); } catch (IOException logOrIgnore) {}
}
String start = "<div class=\"post-text\"><p>";
String end = "</p>";
String part = builder.substring(builder.indexOf(start) + start.length());
String question = part.substring(0, part.indexOf(end));
System.out.println(question);
}
Run Code Online (Sandbox Code Playgroud)
在几乎所有情况下,解析肯定比模式匹配更快.模式匹配更容易,但是在使用复杂的正则表达式模式时,它可能会产生意外结果.
您还可以考虑使用更灵活的第三方HTML解析器,而不是自己编写一个.它不会像使用事先已知的信息解析自己那么快.然而,它将更加简洁和灵活.使用体面的HTML解析器,速度差异可以忽略不计.我强烈推荐Jsoup.它支持类似jQuery的CSS选择器.提取问题的第一段将非常简单:
public static void main(String... args) throws Exception {
Document document = Jsoup.connect("http://stackoverflow.com/questions/2971155").get();
String question = document.select("#question .post-text p").first().text();
System.out.println(question);
}
Run Code Online (Sandbox Code Playgroud)
目前还不清楚你在谈论什么网页,所以我不能给出一个更详细的例子,说明如何使用Jsoup从特定页面中选择特定信息.如果您仍然无法使用Jsoup和CSS选择器自行计算,那么可以随意在评论中发布URL,我会建议如何做到这一点.