web_scrape/scrape/
scraper.rs

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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
use scraper::element_ref::Select;
use scraper::{ElementRef, Selector};

use crate::scrape::Error;
use crate::scrape::Error::*;

/// Responsible for scraping data from elements.
#[derive(Copy, Clone, Debug)]
pub struct Scraper<'a> {
    element: ElementRef<'a>,
}

impl<'a> From<ElementRef<'a>> for Scraper<'a> {
    fn from(element: ElementRef<'a>) -> Self {
        Self { element }
    }
}

impl<'a> Scraper<'a> {
    //! Properties

    /// Gets the element.
    pub fn element(&self) -> ElementRef {
        self.element
    }
}

impl<'a> Scraper<'a> {
    //! Utils

    /// Creates the `Selector` for the `selection`.
    fn selector(selection: &str) -> Result<Selector, Error> {
        Selector::parse(selection).map_err(|e| InvalidSelection {
            selection: selection.to_string(),
            message: e.to_string(),
        })
    }
}

impl<'a> Scraper<'a> {
    //! All

    /// Scrapes all the instances of the `selection`.
    pub fn all<T, F>(&self, selection: &str, scrape: F) -> Result<Vec<T>, Error>
    where
        F: Fn(Scraper) -> Result<T, Error>,
    {
        let selector: Selector = Self::selector(selection)?;
        let mut result: Vec<T> = Vec::default();
        for element in self.element.select(&selector) {
            let scraper: Scraper = Scraper::from(element);
            let element: T = scrape(scraper)?;
            result.push(element)
        }
        Ok(result)
    }

    /// Scrapes all the text from the `selection`.
    pub fn all_text(&self, selection: &str) -> Result<Vec<String>, Error> {
        self.all(selection, |s| Ok(s.element().text().collect()))
    }

    /// Scrapes all the html from the `selection`.
    pub fn all_html(&self, selection: &str) -> Result<Vec<String>, Error> {
        self.all(selection, |s| Ok(s.element().html()))
    }

    /// Scrapes all the successful instances of the `selection`.
    pub fn all_flat<T, F>(&self, selection: &str, scrape: F) -> Result<Vec<T>, Error>
    where
        F: Fn(Scraper) -> Result<Option<T>, Error>,
    {
        let selector: Selector = Self::selector(selection)?;
        let mut result: Vec<T> = Vec::default();
        for element in self.element.select(&selector) {
            let scraper: Scraper = Scraper::from(element);
            if let Some(element) = scrape(scraper)? {
                result.push(element)
            }
        }
        Ok(result)
    }
}

impl<'a> Scraper<'a> {
    //! Only

    /// Scrapes the only instance of the `selection`.
    pub fn only<T, F>(&self, selection: &str, scrape: F) -> Result<T, Error>
    where
        F: Fn(Scraper) -> Result<T, Error>,
    {
        let selector: Selector = Self::selector(selection)?;
        let mut select: Select = self.element.select(&selector);
        if let Some(first) = select.next() {
            let first: T = scrape(first.into())?;
            if select.next().is_some() {
                Err(ExpectedOneGotMultiple {
                    selection: selection.to_string(),
                })
            } else {
                Ok(first)
            }
        } else {
            Err(ExpectedOneGotNone {
                selection: selection.to_string(),
            })
        }
    }

    /// Scrapes the only instance of the `selection` attribute.
    pub fn only_att(&self, selection: &str, att: &str) -> Result<String, Error> {
        self.only(selection, |s| {
            if let Some(att) = s.element.attr(att) {
                Ok(att.to_string())
            } else {
                Err(ExpectedOneGotNone {
                    selection: selection.to_string(),
                })
            }
        })
    }

    /// Scrapes the only instance of the `selection` text.
    pub fn only_text(&self, selection: &str) -> Result<String, Error> {
        self.only(selection, |s| Ok(s.element.text().collect()))
    }
}

impl<'a> Scraper<'a> {
    //! Optional

    /// Scrapes the optional instance of the `selection`.
    pub fn optional<T, F>(&self, selection: &str, scrape: F) -> Result<Option<T>, Error>
    where
        F: Fn(Scraper) -> Result<T, Error>,
    {
        let selector: Selector = Self::selector(selection)?;
        let mut select: Select = self.element.select(&selector);
        if let Some(first) = select.next() {
            let first: T = scrape(first.into())?;
            if select.next().is_some() {
                Err(ExpectedOptionalGotMultiple {
                    selection: selection.to_string(),
                })
            } else {
                Ok(Some(first))
            }
        } else {
            Ok(None)
        }
    }

    /// Scrapes the optional instance of the `selection` text.
    pub fn optional_text(&self, selection: &str) -> Result<Option<String>, Error> {
        self.optional(selection, |s| Ok(s.element().text().collect()))
    }
}