【发布时间】:2012-08-11 01:54:19
【问题描述】:
public class Parser {
public static void main(String[] args) {
Parser p = new Parser();
p.matchString();
}
parserObject courseObject = new parserObject();
ArrayList<parserObject> courseObjects = new ArrayList<parserObject>();
ArrayList<String> courseNames = new ArrayList<String>();
String theWebPage = " ";
{
try {
URL theUrl = new URL("http://ocw.mit.edu/courses/");
BufferedReader reader =
new BufferedReader(new InputStreamReader(theUrl.openStream()));
String str = null;
while((str = reader.readLine()) != null) {
theWebPage = theWebPage + " " + str;
}
reader.close();
} catch (MalformedURLException e) {
// do nothing
} catch (IOException e) {
// do nothing
}
}
public void matchString() {
// this is my regex that I am using to compare strings on input page
String matchRegex = "#\\w+(-\\w+)+";
Pattern p = Pattern.compile(matchRegex);
Matcher m = p.matcher(theWebPage);
int i = 0;
while (!m.hitEnd()) {
try {
System.out.println(m.group());
courseNames.add(i, m.group());
i++;
} catch (IllegalStateException e) {
// do nothing
}
}
}
}
我想用上面的代码实现的是获取 MIT OpencourseWare 网站上的部门列表。我正在使用与页面源中的部门名称模式匹配的正则表达式。我正在使用 Pattern 对象和 Matcher 对象并尝试 find() 并打印这些与正则表达式匹配的部门名称。但是代码需要永远运行,我不认为使用 bufferedReader 在网页中阅读需要那么长时间。所以我认为我要么做错了什么,要么解析网站需要很长时间。因此,如果有任何关于如何提高性能或纠正我的代码中的错误的意见,我将不胜感激。对于写得不好的代码,我深表歉意。
【问题讨论】:
-
你可以为每个页面下载和解析分离线程
-
是的,我考虑过,也许我可能不得不这样做。然而,这非常令人惊讶,因为这甚至不是一个完整的网站,只是我目前正在使用的一个网页,虽然内容很多,但它仍然不应该花那么长时间。
-
您是否在没有 BufferedReader 的情况下绑定,只是将 InputStream 直接读取到字节数组中?
标签: java regex web-crawler