我正在开发一个项目来爬行一个小型网络目录,并使用crawler4j实现了一个爬虫。我知道 RobotstxtServer 应该检查 robots.txt 文件是否允许/禁止某个文件,但我的仍然显示不应访问的目录。
我已经多次阅读源代码和我的代码,但我似乎无法弄清楚这是为什么。简而言之,为什么我的程序无法识别 robots.txt 文件规定不要执行的/donotgohere/文件?
下面是我的程序代码。任何帮助都是极好的。谢谢!
爬虫:
package crawler_Project1_AndrewCranmer;
import java.util.Set;
import java.util.regex.Pattern;
import java.io.IOException;
import edu.uci.ics.crawler4j.crawler.Page;
import edu.uci.ics.crawler4j.crawler.WebCrawler;
import edu.uci.ics.crawler4j.parser.HtmlParseData;
import edu.uci.ics.crawler4j.url.WebURL;
public class MyCrawler extends WebCrawler
{
private final static Pattern FILTERS = Pattern.compile(".*(\\.(css|js|gif|jpg|png|mp3|mp3|zip|gz))$");
@Override public boolean shouldVisit(Page referringPage, WebURL url)
{
String href = url.getURL().toLowerCase();
return !FILTERS.matcher(href).matches()
&& href.startsWith("http://lyle.smu.edu/~fmoore");
}
@Override public void visit(Page page)
{
String url = page.getWebURL().getURL();
System.out.println("URL: " + url);
if(page.getParseData() instanceof HtmlParseData)
{
HtmlParseData h = (HtmlParseData)page.getParseData();
String text = h.getText();
String html = h.getHtml();
Set<WebURL> links = h.getOutgoingUrls();
}
}
}
Controller :
package crawler_Project1_AndrewCranmer;
import edu.uci.ics.crawler4j.crawler.CrawlConfig;
import edu.uci.ics.crawler4j.crawler.CrawlController;
import edu.uci.ics.crawler4j.fetcher.PageFetcher;
import edu.uci.ics.crawler4j.robotstxt.RobotstxtConfig;
import edu.uci.ics.crawler4j.robotstxt.RobotstxtServer;
public class Controller
{
public static void main(String[] args) throws Exception
{
int numberOfCrawlers = 1;
String crawlStorageFolder = "/data/crawl/root";
CrawlConfig c = new CrawlConfig();
c.setCrawlStorageFolder(crawlStorageFolder);
c.setMaxDepthOfCrawling(-1); //Unlimited Depth
c.setMaxPagesToFetch(-1); //Unlimited Pages
c.setPolitenessDelay(200); //Politeness Delay
PageFetcher pf = new PageFetcher(c);
RobotstxtConfig robots = new RobotstxtConfig();
RobotstxtServer rs = new RobotstxtServer(robots, pf);
CrawlController controller = new CrawlController(c, pf, rs);
controller.addSeed("http://lyle.smu.edu/~fmoore");
controller.start(MyCrawler.class, numberOfCrawlers);
controller.shutdown();
controller.waitUntilFinish();
}
}
最佳答案
crawler4j
使用 URL 规范化过程。根据robotstxt.org网站(事实上的标准)仅指定域根目录中的 robots.txt
文件。因此,crawler4j
将仅在那里搜索 robots.txt
。
在您的情况下,http://lyle.smu.edu/
未在 http://lyle.smu.edu 提供
(这将给出 HTTP 404)。robots.txt
/robots.txt
您的robots.txt
位于http://lyle.smu.edu/~fmoore/robots.txt
,但框架只会查看域root(按照事实上的标准指定)来查找该文件。因此,它将忽略您案例中声明的指令。
关于java - crawler4j 似乎忽略了 robots.txt 文件...如何修复它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35852746/