在Eclipse项目中使用WebCollector爬虫非常简单,不需要任何其他的配置,只需要导入相关的jar包即可。
Netbeans、Intellij也是非常优秀的IDE,下面的方法也同样适用于Netbeans和Intellij(有细微差别),推荐使用Netbeans或Intellij。至于Netbeans和Intellij的项目结构是否通用这个问题,其实是不用考虑的,因为Eclipse项目结构也是不通用的,参与过开源软件开发的人应该知道,apache等开源组织发布的源码往往是ant项目或maven项目,这些才是通用的项目结构,并且Netbeans和Intellij在对ant和maven的支持上,比Eclipse好得多。
1.直接使用配置好的项目:
WebCollector爬取新浪微博等完整示例工程可加群250108697或345054141从群文件中下载,下载群文件中任意WebCollector示例项目即可。
2.自己动手配置项目:
具体步骤如下:
1.进入WebCollector官方网站下载最新版本所需jar包。
最新版本的jar包放在webcollector-version-bin.zip中。
2.打开Eclipse,选择File->New->Java Project,按照正常步骤新建一个JAVA项目。
在工程根目录下新建一个文件夹lib,将刚下载的webcollector-version-bin.zip解压后得到的所有jar包放到lib文件夹下。将jar包放到build path中。
3.现在可以编写WebCollector爬虫的代码了,例如我们编写一个爬取网站新闻的例子。
新建一个类NewsCrawler.java,源码如下:
import cn.edu.hfut.dmic.webcollector.model.CrawlDatums; import cn.edu.hfut.dmic.webcollector.model.Page; import cn.edu.hfut.dmic.webcollector.plugin.berkeley.BreadthCrawler; import org.jsoup.nodes.Document; /** *
* 来自合肥工业大学的消息
* @author hu */ public class NewsCrawler extends BreadthCrawler { /** * @param crawlPath
* 这是crawler的信息 * @param
* autoParse
* = true 代表如果可以自动解析,则BreadthCrawler会自动提取
* 从这个页面用正则表达式去匹配链接
* 这是一个构造函数
*/
public NewsCrawler(String crawlPath, boolean autoParse) {
super(crawlPath, autoParse);
/*页面开始*/
this.addSeed("http://news.hfut.edu.cn/list-1-1.html");
/*获取像这样的http://news.hfut.edu.cn/show-xxxxxxhtmlurl*/
this.addRegex("http://news.hfut.edu.cn/show-.*html");
/*不获取这样的格式 jpg|png|gif*/
this.addRegex("-.*\\.(jpg|png|gif).*");
/*也不要这样的 #*/
this.addRegex("-.*#.*");
}
@Override
public void visit(Page page, CrawlDatums next) {
String url = page.getUrl();
/*如果是一个新的页面*/
if (page.matchUrl("http://news.hfut.edu.cn/show-.*html")) {
/*用JSOUP去解析这个页面*/
Document doc = page.getDoc();
/*的提取新闻和标题的css选择器*/
String title = page.select("div[id=Article]>h2").first().text();
String content = page.select("div#artibody", 0).text();
System.out.println("URL:\n" + url);
System.out.println("title:\n" + title);
System.out.println("content:\n" + content);
/*如果你想要抓取新的url,添加他们到 nextLink*/
/*WebCollector 可以自动去重*/
/*如果autoparse 为真则添加链接去nextlinks 如果与正则不匹配则不会添加*/
//next.add("http://xxxxxx.com");
}
}
public static void main(String[] args) throws Exception {
NewsCrawler crawler = new NewsCrawler("crawl", true);
crawler.setThreads(50);
crawler.setTopN(100);
//crawler.setResumable(true);
/*网页爬取深度为4*/
crawler.start(4);
}
}
4.运行源码即可看到输出
http://datahref.com/archives/10 原文地址 我只是把注解翻译过来 英语不好 看不懂的去原文