1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
use cfg_if::cfg_if;
use lazy_static::lazy_static;
use scraper::{ElementRef, Html, Selector};
use std::borrow::Cow;
use std::convert::TryFrom;
use std::error::Error;
mod native;
cfg_if! {
if #[cfg(feature = "ffi")] {
mod ffi;
pub use ffi::*;
use rmp_serde::{to_vec, to_vec_named};
use serde::Serialize;
} else {
pub use native::*;
}
}
#[derive(Debug)]
#[cfg_attr(feature = "ffi", derive(Serialize))]
pub struct GResult {
title: String,
link: String,
description: String,
}
lazy_static! {
static ref LINK_SELECT: Selector =
Selector::parse("div.mw div.col .bkWMgd div.srg div.g div div.rc div.r a cite.iUh30")
.unwrap();
static ref TITLE_SELECT: Selector = Selector::parse(".LC20lb").unwrap();
static ref DESCRIPTION_SELECT: Selector = Selector::parse("div.s").unwrap();
}
impl TryFrom<ElementRef<'_>> for GResult {
type Error = Box<dyn Error + Send + Sync>;
fn try_from(value: ElementRef) -> Result<Self, Self::Error> {
let srch_result = value
.ancestors()
.nth(4)
.and_then(ElementRef::wrap)
.ok_or("Couldnt get search node")?;
let title = srch_result
.select(&TITLE_SELECT)
.next()
.ok_or("Cant get title")?
.text()
.collect::<String>();
let link = value.text().collect::<String>();
let description = srch_result
.select(&DESCRIPTION_SELECT)
.next()
.ok_or("Cant get description")?
.text()
.collect::<String>();
Ok(GResult {
title,
link,
description,
})
}
}