Search code examples
web-scrapingrusthrefrust-cargo

How do I get "href" value of an "a" tag using scaper in Rust?


I have a Rust project that used the "scraper" library. I want to get the href value of an a tag element from a website. It is not shown in the documentation how to do it. I tried the below code but it only returned the inner HTML content.

let result_sites: scraper::Selector =
        scraper::Selector::parse("a.s-topbar--logo").unwrap();

What is the best way to get the href value?


Solution

  • use scraper::{Html, Selector};
    
    let html = r#"..."#;
    let fragment = Html::parse_fragment(html);
    let sites_selector = Selector::parse("a.s-topbar--logo").unwrap();
    
    for el in fragment.select(&sites_selector) {
        let href = el.value().attr("href").unwrap();
        println!("{:?}", href);
    }
    
    

    Here is the documentation with example