crawler4j Documentation
repository·master·Indexed 26 days ago
https://github.com/yasserg/crawler4jA multi-threaded web crawler library for Java. It provides a simple interface for setting up crawlers by extending the WebCrawler class and configuring the CrawlController. Features include support for JDBC-compliant databases like PostgreSQL, customizable crawl depth, politeness delays, and proxy configuration. Version 4.4.0 is available via Maven and Gradle.
What's inside crawler4j
- crawler4j is an open source web crawler for Java which provides a simple interface for crawling the Web. Using it, you can setup a multi-threaded web crawler in few minutes.
Configure and start a CrawlController
masterTo run a crawl, implement a controller that sets up the
CrawlConfig,PageFetcher,RobotstxtServer, andCrawlController.Steps:
- Create a
CrawlConfigand set thecrawlStorageFolder. - Instantiate
PageFetcher,RobotstxtConfig, andRobotstxtServer. - Initialize
CrawlControllerwith the config, fetcher, and server. - Add seed URLs using
controller.addSeed(url). - Provide a
WebCrawlerFactory(e.g., using a method reference to your crawler constructor). - Call
controller.start(factory, numberOfCrawlers)to begin the blocking crawl operation.
public class Controller { public static void main(String[] args) throws Exception { String crawlStorageFolder = "/data/crawl/root"; int numberOfCrawlers = 7; CrawlConfig config = new CrawlConfig(); config.setCrawlStorageFolder(crawlStorageFolder); // Instantiate the controller for this crawl. PageFetcher pageFetcher = new PageFetcher(config); RobotstxtConfig robotstxtConfig = new RobotstxtConfig(); RobotstxtServer robotstxtServer = new RobotstxtServer(robotstxtConfig, pageFetcher); CrawlController controller = new CrawlController(config, pageFetcher, robotstxtServer); // Add seed urls. controller.addSeed("https://www.ics.uci.edu/~lopes/"); controller.addSeed("https://www.ics.uci.edu/~welling/"); controller.addSeed("https://www.ics.uci.edu/"); // The factory which creates instances of crawlers. CrawlController.WebCrawlerFactory<BasicCrawler> factory = MyCrawler::new; // Start the crawl. controller.start(factory, numberOfCrawlers); } }- Create a
Install crawler4j via Maven or Gradle
masterTo use crawler4j in your Java project, add the dependency to your build configuration file.
Maven
Add the following to your
pom.xml:Gradle
Add the following to your
build.gradlefile:<!-- Maven --> <dependency> <groupId>edu.uci.ics</groupId> <artifactId>crawler4j</artifactId> <version>4.4.0</version> </dependency> <!-- Gradle --> compile group: 'edu.uci.ics', name: 'crawler4j', version: '4.4.0'Fix surefire test failures on Windows (Docker not found)
masterIf your surefire tests fail on Windows becausedocker.exeordocker-compose.execannot be found, you must manually specify their locations. Create a.mvn/maven.configfile at the project root (two levels higher than the example folder) and add the following configuration. Ensure the paths match your local Docker installation.Save crawled pages to a JDBC repository
masterThis sample demonstrates how to integrate crawler4j with a JDBC repository to persist crawled page data into a database (e.g., PostgreSQL).Implement a custom WebCrawler
masterTo define crawling logic, extend the
WebCrawlerclass and override two primary methods:shouldVisit(Page referringPage, WebURL url): Returnstrueif the URL should be crawled. Use this to implement filters (e.g., file extensions or domain restrictions).visit(Page page): Called after a page is successfully downloaded. Use this to process the content. You can access the URL, text, HTML, and outgoing links via thePageobject.
If the page is HTML, you can cast
page.getParseData()toHtmlParseDatato accessgetText(),getHtml(), andgetOutgoingUrls().public class MyCrawler extends WebCrawler { private final static Pattern FILTERS = Pattern.compile(".*(\.(css|js|gif|jpg" + "|png|mp3|mp4|zip|gz))$"); @Override public boolean shouldVisit(Page referringPage, WebURL url) { String href = url.getURL().toLowerCase(); return !FILTERS.matcher(href).matches() && href.startsWith("https://www.ics.uci.edu/"); } @Override public void visit(Page page) { String url = page.getWebURL().getURL(); System.out.println("URL: " + url); if (page.getParseData() instanceof HtmlParseData) { HtmlParseData htmlParseData = (HtmlParseData) page.getParseData(); String text = htmlParseData.getText(); String html = htmlParseData.getHtml(); Set<WebURL> links = htmlParseData.getOutgoingUrls(); System.out.println("Text length: " + text.length()); System.out.println("Html length: " + html.length()); System.out.println("Number of outgoing links: " + links.size()); } } }Configure CrawlConfig options
masterUse the
CrawlConfigclass to tune the crawler's behavior. Key configuration methods include:Method Description setMaxDepthOfCrawling(int)Limits how many links deep the crawler will follow. setIncludeHttpsPages(boolean)Enables/disables SSL/HTTPS crawling. setMaxPagesToFetch(int)Sets a hard limit on the total number of pages to crawl. setIncludeBinaryContentInCrawling(boolean)Enables crawling of images, audio, etc. setPolitenessDelay(long)Sets the delay (in milliseconds) between requests to avoid overloading servers. setProxyHost(String)/setProxyPort(int)Configures a proxy server. setProxyUsername(String)/setProxyPassword(String)Configures proxy authentication. setResumableCrawling(boolean)Allows resuming a previously stopped or crashed crawl. setUserAgentString(String)Overwrites the default crawler4j user agent string.