我需要使用 Crawler4j 从网站下载 PDF。我正在关注this documentation创建两个类:
PDFCrawler
PDFCrawlController
现在,在我的 PDFCrawler
类中,我有一个 shouldVisit(Page page, WebURL url)
方法,如下所示:
public boolean shouldVisit(Page page, WebURL url) {
String href = url.getURL().toLowerCase();
return href.startsWith(crawlDomain) && pdfPatterns.matcher(href).matches();
}
此处,crawlDomain
是从 PDFCrawlController
类发送的域(例如,http://www.example.com
)。 pdfPatterns
定义如下:
private static final Pattern pdfPatterns = Pattern.compile(".*(\\.(pdf?))$");
PDFCrawler
类中的 visit(Page page)
方法如下所示:
public void visit(Page page) {
String url = page.getWebURL().getURL();
if (!pdfPatterns.matcher(url).matches()) {
System.out.println("I am in " + url);
System.out.println("No match. Leaving.");
return;
}
//and so on...
}
现在,当我将 http://www.example.com
发送到 PDFCrawler
时,System.out.println()
在 visit(Page page)
方法中打印如下:
I am in http://www.example.com/allforgood
No match. Leaving.
I am in http://www.another-web-site.iastate.edu/grants/xp2011-02
No match. Leaving.
I am in http://www.example.com/careers
No match. Leaving.
I am in http://www.example.com/wp-content/uploads/2014/01/image-happenings1.png
No match. Leaving.
我的问题是:
- 为什么抓取工具要访问
另一个网站
?我不是在shouldVisit()
方法中限制它这样做吗? - 为什么它访问的页面实际上是图像(例如
png
)?我不是在shouldVisit()
方法中限制它这样做吗?
最佳答案
您的 shouldVisit
函数没有被调用。它没有针对最新版本的正确声明。您正在遵循该示例,但该示例是错误的。
唯一的参数是 URL。可以在API here中看到.
此外,当您使用 @Override
表示法时,您可以捕获类似的内容。 Java 会告诉您,您实际上并没有覆盖您想要覆盖的内容。
关于java - 需要澄清Crawler4j的shouldVisit和visit方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29522891/