29 releases

0.1.28 Apr 1, 2022
0.1.27 Jan 8, 2022
0.1.23 Dec 22, 2021
0.1.22 Jul 8, 2021
0.1.11 Mar 11, 2020

#346 in Web programming

Download history 159/week @ 2022-04-27 196/week @ 2022-05-04 444/week @ 2022-05-11 125/week @ 2022-05-18 124/week @ 2022-05-25 237/week @ 2022-06-01 67/week @ 2022-06-08 13/week @ 2022-06-15 14/week @ 2022-06-22 7/week @ 2022-06-29 36/week @ 2022-07-06 66/week @ 2022-07-13 37/week @ 2022-07-20 103/week @ 2022-07-27 75/week @ 2022-08-03 19/week @ 2022-08-10

236 downloads per month

MIT license

21KB
435 lines

Crabler - Web crawler for Crabs

CI Crates.io docs.rs MIT licensed

Asynchronous web scraper engine written in rust.

Features:

  • fully based on async-std
  • derive macro based api
  • struct based api
  • stateful scraper (structs can hold state)
  • ability to download files
  • ability to schedule navigation jobs in an async manner

Example

extern crate crabler;

use std::path::Path;

use crabler::*;
use surf::Url;

#[derive(WebScraper)]
#[on_response(response_handler)]
#[on_html("a[href]", walk_handler)]
struct Scraper {}

impl Scraper {
    async fn response_handler(&self, response: Response) -> Result<()> {
        if response.url.ends_with(".png") && response.status == 200 {
            println!("Finished downloading {} -> {:?}", response.url, response.download_destination);
        }
        Ok(())
    }

    async fn walk_handler(&self, mut response: Response, a: Element) -> Result<()> {
        if let Some(href) = a.attr("href") {
            // Create absolute URL
            let url = Url::parse(&href)
                .unwrap_or_else(|_| Url::parse(&response.url).unwrap().join(&href).unwrap());

            // Attempt to download an image
            if href.ends_with(".png") {
                let image_name = url.path_segments().unwrap().last().unwrap();
                let p = Path::new("/tmp").join(image_name);
                let destination = p.to_string_lossy().to_string();

                if !p.exists() {
                    println!("Downloading {}", destination);
                    // Schedule crawler to download file to some destination
                    // downloading will happen in the background, await here is just to wait for job queue
                    response.download_file(url.to_string(), destination).await?;
                } else {
                    println!("Skipping existing file {}", destination);
                }
            } else {
              // Or schedule crawler to navigate to a given url
              response.navigate(url.to_string()).await?;
            };
        }

        Ok(())
    }
}

#[async_std::main]
async fn main() -> Result<()> {
    let scraper = Scraper {};

    // Run scraper starting from given url and using 20 worker threads
    scraper.run(Opts::new().with_urls(vec!["https://www.rust-lang.org/"]).with_threads(20)).await
}

Sample project

Gonzih/apod-nasa-scraper-rs

Dependencies

~9–16MB
~306K SLoC