Giter VIP home page Giter VIP logo

crusty-core's Introduction

crates.io Dependency status

Crusty-core - build your own web crawler!

Example - crawl single website, collect information about TITLE tags

use crusty_core::{prelude::*, select_task_expanders::FollowLinks};

#[derive(Debug, Default)]
pub struct JobState {
    sum_title_len: usize,
}

#[derive(Debug, Clone, Default)]
pub struct TaskState {
    title: String,
}

pub struct DataExtractor {}
type Ctx = JobCtx<JobState, TaskState>;
impl TaskExpander<JobState, TaskState, Document> for DataExtractor {
    fn expand(
        &self,
        ctx: &mut Ctx,
        _: &Task,
        _: &HttpStatus,
        doc: &Document,
    ) -> task_expanders::Result {
        if let Some(title) = doc.find(Name("title")).next().map(|v| v.text()) {
            ctx.job_state.lock().unwrap().sum_title_len += title.len();
            ctx.task_state.title = title;
        }
        Ok(())
    }
}

#[tokio::main]
async fn main() -> anyhow::Result<()> {
    let crawler = Crawler::new_default()?;

    let settings = config::CrawlingSettings::default();
    let rules = CrawlingRules::new(CrawlingRulesOptions::default(), document_parser())
        .with_task_expander(|| DataExtractor {})
        .with_task_expander(|| FollowLinks::new(LinkTarget::HeadFollow));

    let job = Job::new("https://example.com", settings, rules, JobState::default())?;
    for r in crawler.iter(job) {
        println!("- {}, task state: {:?}", r, r.ctx.task_state);
        if let JobStatus::Finished(_) = r.status {
            println!("final job state: {:?}", r.ctx.job_state.lock().unwrap());
        }
    }
    Ok(())
}

If you want to get more fancy and configure some stuff or control your imports more precisely

use crusty_core::{
    config,
    select::predicate::Name,
    select_task_expanders::{document_parser, Document, FollowLinks},
    task_expanders,
    types::{HttpStatus, Job, JobCtx, JobStatus, LinkTarget, Task},
    Crawler, CrawlingRules, CrawlingRulesOptions, ParserProcessor, TaskExpander,
};

#[derive(Debug, Default)]
pub struct JobState {
    sum_title_len: usize,
}

#[derive(Debug, Clone, Default)]
pub struct TaskState {
    title: String,
}

pub struct DataExtractor {}
type Ctx = JobCtx<JobState, TaskState>;
impl TaskExpander<JobState, TaskState, Document> for DataExtractor {
    fn expand(
        &self,
        ctx: &mut Ctx,
        _: &Task,
        _: &HttpStatus,
        doc: &Document,
    ) -> task_expanders::Result {
        let title = doc.find(Name("title")).next().map(|v| v.text());
        if let Some(title) = title {
            ctx.job_state.lock().unwrap().sum_title_len += title.len();
            ctx.task_state.title = title;
        }
        Ok(())
    }
}

#[tokio::main]
async fn main() -> anyhow::Result<()> {
    let concurrency_profile = config::ConcurrencyProfile::default();
    let parser_profile = config::ParserProfile::default();
    let tx_pp = ParserProcessor::spawn(concurrency_profile, parser_profile);

    let networking_profile = config::NetworkingProfile::default().resolve()?;
    let crawler = Crawler::new(networking_profile, tx_pp);

    let settings = config::CrawlingSettings::default();
    let rules_opt = CrawlingRulesOptions::default();
    let rules = CrawlingRules::new(rules_opt, document_parser())
        .with_task_expander(|| DataExtractor {})
        .with_task_expander(|| FollowLinks::new(LinkTarget::HeadFollow));

    let job = Job::new("https://example.com", settings, rules, JobState::default())?;
    for r in crawler.iter(job) {
        println!("- {}, task state: {:?}", r, r.ctx.task_state);
        if let JobStatus::Finished(_) = r.status {
            println!("final job state: {:?}", r.ctx.job_state.lock().unwrap());
        }
    }

    Ok(())
}

Install

Simply add this to your Cargo.toml

[dependencies]
crusty-core = {version = "~0.82.0", features=["select_rs"]}

if you need just library without built-in select.rs task expanders(for links, images, etc)

[dependencies]
crusty-core = "~0.82.0"

Key capabilities

  • multi-threaded && async on top of tokio
  • highly customizable filtering at each and every step
    • custom dns resolver with builtin IP/subnet filtering
    • status code/headers received(built-in content-type filters work at this step),
    • page downloaded(say we can decide not to parse DOM),
    • task filtering, complete control on -what- to follow and -how- to(just resolve dns, head, head+get)
  • built on top of hyper (http2 and gzip/deflate baked in)
  • rich content extraction with select
  • observable with tracing and custom metrics exposed to user(stuff like html parsing duration, bytes sent/received)
  • lots of options, almost everything is configurable either through options or code
  • applicable both for focused and broad crawling
  • scales with ease when you want to crawl millions/billions of domains
  • it's fast, fast, fast!

Development

  • make sure python3 and pip are installed

  • make sure rustup is installed: https://rustup.rs/

  • run ./go setup

  • run ./go check to run all pre-commit hooks and ensure everything is ready to go for git

  • run ./go release minor to release a next minor version for crates.io

Notes

Please see examples for more complicated usage scenarios. This crawler is more verbose than some others, but it allows incredible customization at each and every step.

If you are interested in the area of broad web crawling there's crusty, developed fully on top of crusty-core that tries to tackle on some challenges of broad web crawling

crusty-core's People

Contributors

let4be avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

Forkers

ousado

crusty-core's Issues

Async channel based DNS resolver

Built on top of StaticAsyncResolver trying to resolve DNS by sending request and awaiting response on a channel, within timeout.

Implement non concurrent crawler

For broad web crawling we probably do not need any concurrency within a single job... which means we can save up a bunch of resources and annoy site owners less...
Additionally I'm considering using this in a so called "breeder" - a dedicated non-concurrent web crawler which purposes are

  • download && parse robots.txt, while
  • resolving redirects
  • resolving additional DNS requests(if any) as long as it falls within the same addr_key, see #14
  • head index page to figure out if there are any redirects(if allowed by robots.txt)
  • Jobs that resolved all DNS(within our restrictions) and successfully HEAD index page are considered "breeded"

all jobs extracted from JobQ will be added to a breeder first and only then to a typical web crawler(if they survive the breeding process) with a StaticDnsResolver(breeder and regular web crawler will have quite different rules and settings)

DNS resolving should be handled as a separate LinkTarget

This would allow for fancier filtering and additional logic, like for example in broad web crawler we might want to "discover" only reservable external domains, crusty-core could handle this resolution

Also should be useful for ip/subnet filtering if we want to restrict crawling certain subnets for example(not necessary just reserved ipv4/ipv6 addresses)

Unify calling and handling of filters

There's a big chunk of duplicated functionality between calling status_filters/load_filters && task_expanders
as soon as #9 && #8 are ready
this functionality becomes generic enough to be consolidated

Cleanup code

  • Simplify String/&str && get rid of excessive memory allocations
  • Get rid of excessive .clone() calls

Rethink format of exposed data

We should not mangle data returned by server if there were no errors in getting it.
Actual errors are different from errors in filters/expanders

Improve status_filters and their errors

  • In particular we should change how we handle max_redirect,

this should be happening in status_filter(when redirect is being emitted) not in task_filter as it's now
so that we could properly record a typed error and later compare against it in Crusty(proper metrics)

  • redirect status filter should always emit TERM when redirect is detected

Support for fully customizable parsing

Right now we use select for html parsing, it's nice and everything but there are different use cases

For low volume crawling it might be a very good fit, but for broad crawling I'm considering switching to something lower level. So crusty-core should support configurable html parsers(and properly propagate it to task_expanders via generics)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.