The PageProcessor interface is part of webmagic-core. To implement custom crawling logic, implement this interface and use the process(Page page) method to define how to extract data and find new URLs.
Key methods within process:
page.getHtml().links().regex(pattern).all(): Finds new URLs matching a regex pattern.page.addTargetRequests(links): Adds discovered URLs to the crawler's queue.page.putField(key, value): Saves extracted data into the page object.page.getHtml().xpath(expression): Extracts data using XPath.page.getHtml().$(selector): Extracts data using CSS selectors.
Use the Spider class to run your crawler.
public class OschinaBlogPageProcessor implements PageProcessor {
private Site site = Site.me().setDomain("my.oschina.net");
@Override
public void process(Page page) {
// 1. Find new links and add them as targets
List<String> links = page.getHtml().links().regex("http://my\.oschina\.net/flashsword/blog/\d+").all();
page.addTargetRequests(links);
// 2. Extract data and put it into fields
page.putField("title", page.getHtml().xpath("//div[@class='BlogEntity']/div[@class='BlogTitle']/h1").toString());
page.putField("content", page.getHtml().$("div.content").toString());
page.putField("tags", page.getHtml().xpath("//div[@class='BlogTags']/a/text()").all());
}
@Override
public Site getSite() {
return site;
}
public static void main(String[] args) {
Spider.create(new OschinaBlogPageProcessor())
.addUrl("http://my.oschina.net/flashsword/blog")
.addPipeline(new ConsolePipeline())
.run();
}
}