Find a html element with id with scraper

Hello,
how can I find a element with a special id in HTML with scraper?
HTML:

<tr id="12345678">
...
</tr>

Rust:

let isin_selector = scraper::Selector::parse("tr#12345678").unwrap();  
let v:Vec<_>=document.select(&isin_selector).collect();
if v.len()>0
{
            //exists
}
else 
{
            //nope
}

Since 12345678 starts with a digit, it is not a valid CSS identifier, and it cannot be used in a CSS ID selector. Therefore, you must use an attribute selector with the id attribute, e.g., Selector::parse("tr[id='12345678']"). Alternatively, you can filter the list of results based on the id attribute:

let tr_selector = Selector::parse("tr").unwrap();
let element = document
    .select(&tr_selector)
    .find(|element| element.value().attr("id") == Some("12345678"));
if let Some(element) = element {
    println!("found element: {}", element.html());
} else {
    println!("did not find element");
}
3 Likes

Thank you. Both versions work.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.