There is approximately such a piece of site parser code using select :
extern crate select; use select::document::Document; use select::predicate::{Class, Name, And}; fn main() { // Пример; реальность чуть сложнее, но не суть let html = "<main> <div class='vote-topic'> <div class='vote-item vote-count'> <span id='vote_total_blog_123'>+15.00</span> </div> </div> </main>"; let page = Document::from(html); let blog_id: u32 = page.find(And(Name("div"),Class("vote-item"))) .find(Name("span")).first() .unwrap().attr("id") .unwrap().split('_').collect::<Vec<_>>().last() .unwrap().parse::<u32>().unwrap(); println!("Blog id: {}", blog_id); } I tried to rewrite it so that at the output I get Option (which I will then transfer to Result; it’s not exactly interested in storing the exact cause of the error). The result works, but looks, to put it mildly, not very:
let blog_id: Option<u32> = page.find(And(Name("div"),Class("vote-item"))).first() .and_then(|x| x.find(Name("span")).first()) .and_then(|x| x.attr("id").and_then(|x| Some(x.to_string()))) .and_then(|x| x.split('_').collect::<Vec<_>>().last().and_then(|x| Some(x.to_string()))) .and_then(|x| x.parse::<u32>().ok()); match blog_id { Some(i) => println!("Blog id: {}", i), None => println!("Cannot parse blog_id"), }; Is it possible to arrange this somehow more beautifully? If I try to simplify this somehow (especially the nasty to_string), the compiler immediately starts swearing for times of life, borrowing and other rubbish. The use of match or if let , I suspect, will lead to an overwhelming number of ladders, and if they are avoided, then the beauty will not increase much. I also tried to write a macro with a loop, equivalent to constant calls and_then , but it turned out just as ugly and to_string has not gone away.
Ideally, something like this Python equivalent:
try: blog_id = int(page.find("div", {"class": "vote-item"}).\ find("span")[0].\ get("id").\ rsplit("_")[-1]) except Exception: blog_id = None (probably, it's better to just take xpath, but the question is not about that yet :)
?instead oftry!. - aSpex