Multi-threaded Link Checker

Let us use our new knowledge to create a multi-threaded link checker. It should start at a webpage and check that links on the page are valid. It should recursively check other pages on the same domain and keep doing this until all pages have been validated.

For this, you will need an HTTP client such as reqwest. Create a new Cargo project and reqwest it as a dependency with:

$ cargo new link-checker $ cd link-checker $ cargo add --features blocking,rustls-tls reqwest

If cargo add fails with error: no such subcommand, then please edit the Cargo.toml file by hand. Add the dependencies listed below.

You will also need a way to find links. We can use scraper for that:

$ cargo add scraper

Finally, we’ll need some way of handling errors. We use thiserror for that:

$ cargo add thiserror

The cargo add calls will update the Cargo.toml file to look like this:

[dependencies] reqwest = { version = "0.11.12", features = ["blocking", "rustls-tls"] } scraper = "0.13.0" thiserror = "1.0.37"

You can now download the start page. Try with a small site such as https://www.google.org/.

Your src/main.rs file should look something like this:

  1. use reqwest::blocking::{get, Response};
  2. use reqwest::Url;
  3. use scraper::{Html, Selector};
  4. use thiserror::Error;
  5. #[derive(Error, Debug)]
  6. enum Error {
  7. #[error("request error: {0}")]
  8. ReqwestError(#[from] reqwest::Error),
  9. }
  10. fn extract_links(response: Response) -> Result<Vec<Url>, Error> {
  11. let base_url = response.url().to_owned();
  12. let document = response.text()?;
  13. let html = Html::parse_document(&document);
  14. let selector = Selector::parse("a").unwrap();
  15. let mut valid_urls = Vec::new();
  16. for element in html.select(&selector) {
  17. if let Some(href) = element.value().attr("href") {
  18. match base_url.join(href) {
  19. Ok(url) => valid_urls.push(url),
  20. Err(err) => {
  21. println!("On {base_url}: could not parse {href:?}: {err} (ignored)",);
  22. }
  23. }
  24. }
  25. }
  26. Ok(valid_urls)
  27. }
  28. fn main() {
  29. let start_url = Url::parse("https://www.google.org").unwrap();
  30. let response = get(start_url).unwrap();
  31. match extract_links(response) {
  32. Ok(links) => println!("Links: {links:#?}"),
  33. Err(err) => println!("Could not extract links: {err:#}"),
  34. }
  35. }

Run the code in src/main.rs with

$ cargo run

Tasks

  • Use threads to check the links in parallel: send the URLs to be checked to a channel and let a few threads check the URLs in parallel.
  • Extend this to recursively extract links from all pages on the www.google.org domain. Put an upper limit of 100 pages or so so that you don’t end up being blocked by the site.