crawler4j Documentation

repository·master·Indexed 26 days ago

https://github.com/yasserg/crawler4j

A 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.

Tokens
2K
Snippets
3
Records
7
Agent score
39%

What's inside crawler4j

  1. Configure and start a CrawlController

    master

    To run a crawl, implement a controller that sets up the CrawlConfig, PageFetcher, RobotstxtServer, and CrawlController.

    Steps:

    1. Create a CrawlConfig and set the crawlStorageFolder.
    2. Instantiate PageFetcher, RobotstxtConfig, and RobotstxtServer.
    3. Initialize CrawlController with the config, fetcher, and server.
    4. Add seed URLs using controller.addSeed(url).
    5. Provide a WebCrawlerFactory (e.g., using a method reference to your crawler constructor).
    6. 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);
        }
    }
  2. Install crawler4j via Maven or Gradle

    master

    To 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.gradle file:

    <!-- 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'
  3. Implement a custom WebCrawler

    master

    To define crawling logic, extend the WebCrawler class and override two primary methods:

    1. shouldVisit(Page referringPage, WebURL url): Returns true if the URL should be crawled. Use this to implement filters (e.g., file extensions or domain restrictions).
    2. 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 the Page object.

    If the page is HTML, you can cast page.getParseData() to HtmlParseData to access getText(), getHtml(), and getOutgoingUrls().

    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());
             }
        }
    }
  4. Configure CrawlConfig options

    master

    Use the CrawlConfig class to tune the crawler's behavior. Key configuration methods include:

    MethodDescription
    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.