我现在正在尝试使用Java.Now实现一个简单的超文本标记语言网页抓取器,我有一个小问题。假设我有以下HTML片段。
<div id="sr-h-left" class="sr-comp">
<a class="link-gray-underline" id="compare_header" rel="nofollow" href="javascript:i18nCompareProd('/serv/main/buyer/ProductCompare.jsp?nxtg=41980a1c051f-0942A6ADCF43B802');">
<span style="cursor: pointer;" class="sr-h-o">Compare</span>
</a>
</div>
<div id="sr-h-right" class="sr-summary">
<div id="sr-num-results">
<div class="sr-h-o-r">Showing 1 - 30 of 1,439 matches, 我感兴趣的数据是底部显示的整数1.439,我只是想知道如何从HTML中获得这个整数。我现在正在考虑使用正则表达式,然后使用java.util.Pattern来帮助获取数据,但仍然不是很清楚这个过程。如果你们能给我一些关于这个数据收集的提示或想法,我将不胜感激。非常感谢。
发布于 2010-04-11 09:41:34
正则表达式可能是最好的方法。类似于:
Pattern p = Pattern.compile("Showing [0-9,]+ - [0-9,]+ of ([0-9,]+) matches");
Matcher m = p.matches(scrapedHTML);
if(m.matches()) {
int num = Integer.parseInt(m.group(1).replaceAll(",", ""));
// num == 1439
}我不确定您所说的理解“进程”是什么意思,但下面是代码的作用:p是一个正则表达式模式,它与“显示...”线路。m就是将该模式应用于抓取的HTML的结果。如果m.matches()为true,则意味着模式与m.group(1)匹配,并且([0-9,]+)将是模式中的第一个正则表达式组(括号中的表达式),它匹配数字和逗号组成的字符串,因此它将是"1,459“。replaceAll()调用将其转换为" 1459 ",而Integer.parseInt()将其转换为整数1459
发布于 2010-04-11 10:44:39
使用正则表达式解析文本是一种可能。有时,您需要的特定文本位于DOM hiearchy中的特定div中,因此您可以使用xpath表达式来查找您需要的内容。有时,您希望查找特定类的div。这取决于特定的HTML。除了正则表达式之外,一个好的HTML解析器也会派上用场。我用过Jericho HTML,但还有很多其他的。
发布于 2010-04-11 12:04:49
使用HTML解析器获取该部分,然后使用正则表达式删除该部分,直到" of“和"matches”中的部分。这是一个在HtmlUnit帮助下的SSCCE
package com.stackoverflow.q2615727;
import java.text.NumberFormat;
import java.util.Locale;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlElement;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
public class Test {
public static void main(String... args) throws Exception {
WebClient client = new WebClient();
HtmlPage page = client.getPage("http://www.google.com/search?q=html+parser");
HtmlElement results = page.getElementById("resultStats"); // <div id="resultStats">
String text = results.asText(); // Results 1 - 10 of about 2,050,000 for html parser. (0.18 seconds)
String total = text.replaceAll("^(.*about)|(for.*)$", "").trim(); // 2,050,000
Long l = (Long) NumberFormat.getInstance(Locale.ENGLISH).parse(total); // 2050000
System.out.println(l);
}
}在您的特定情况下,您可能只想替换中的URL和以下两行:
HtmlElement results = page.getElementById("sr-num-results"); // <div id="sr-num-results">和
String total = text.replaceAll("^(.*of)|(matches.*)$", "").trim(); // 1,439https://stackoverflow.com/questions/2615727
复制相似问题