skyscraper 0.7.0

XPath for HTML web scraping
Documentation
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
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
//! Parse and apply XPath expressions to HTML documents.
//!
//! Important pages:
//!
//! - [parse] - Parse a string into an [Xpath] expression.
//! - [Xpath::apply] - Apply an [Xpath] expression to an [XpathItemTree].
//! - [XpathItemTree] - A tree of [XpathItem]s that can be searched using an [Xpath] expression.
//!
//! # Example: get links with the `/@href` xpath step
//!
//! ```rust
//! # use std::error::Error;
//! #
//! use skyscraper::html;
//! use skyscraper::xpath;
//!
//! # fn main() -> Result<(), Box<dyn Error>> {
//! let text = r##"
//! <html>
//!     <body>
//!         <a href="https://example1.com">Example 1</a>
//!         <a href="https://example2.com">Example 2</a>
//!     </body>
//! </html>"##;
//!
//! // Parse the HTML text
//! let xpath_item_tree = html::parse(text)?;
//!
//! let xpath = xpath::parse("//a/@href")?;
//!
//! // Apply the XPath expression to our HTML document
//! let items = xpath.apply(&xpath_item_tree)?;
//!
//! let attributes: Vec<&str> = items
//!     .iter()
//!     .map(|item| item
//!         .extract_as_node() // we know it's a node all attributes are on nodes
//!         .extract_as_attribute_node() // we know it's an attribute node
//!         .value
//!         .as_str()
//!     )
//!     .collect();
//!
//! assert_eq!(attributes, vec!["https://example1.com", "https://example2.com"]);
//!
//! # Ok(())
//! # }
//! ```
//!
//! # Example: get links programmatically
//!
//! ```rust
//! # use std::error::Error;
//! #
//! use skyscraper::html;
//! use skyscraper::xpath;
//!
//! # fn main() -> Result<(), Box<dyn Error>> {
//! let text = r##"
//! <html>
//!     <body>
//!         <a href="https://example1.com">Example 1</a>
//!         <a href="https://example2.com">Example 2</a>
//!     </body>
//! </html>"##;
//!
//! // Parse the HTML text
//! let xpath_item_tree = html::parse(text)?;
//!
//! let xpath = xpath::parse("//a")?;
//!
//! // Apply the XPath expression to our HTML document
//! let items = xpath.apply(&xpath_item_tree)?;
//!
//! let attributes: Vec<&str> = items
//!     .iter()
//!     .filter_map(|item| item
//!         .extract_as_node() // we know it's a node
//!         .extract_as_element_node() // we know it's an element node
//!         .get_attribute(&xpath_item_tree, "href")
//!     )
//!     .collect();
//!
//! assert_eq!(attributes, vec!["https://example1.com", "https://example2.com"]);
//!
//! # Ok(())
//! # }
//! ```
//!
//! # Example: get text using the `/text()` xpath step
//!
//! ```rust
//! # use std::error::Error;
//! #
//! use skyscraper::html;
//! use skyscraper::xpath;
//!
//! # fn main() -> Result<(), Box<dyn Error>> {
//! let text = r##"
//! <html>
//!     <body>
//!         <div>Example 1</div>
//!         <div>Example 2</div>
//!     </body>
//! </html>"##;
//!
//! // Parse the HTML text
//! let xpath_item_tree = html::parse(text)?;
//!
//! let xpath = xpath::parse("//div/text()")?;
//!
//! // Apply the XPath expression to our HTML document
//! let items = xpath.apply(&xpath_item_tree)?;
//!
//! let text_contents: Vec<String> = items
//!     .iter()
//!     .map(|item| item
//!         .extract_as_node() // we know it's a node because text is a type of node
//!         .extract_as_text_node() // we know it's a text node
//!         .content
//!         .to_string()
//!     )
//!     .collect();
//!
//! assert_eq!(text_contents, vec!["Example 1", "Example 2"]);
//!
//! # Ok(())
//! # }
//! ```
//!
//! # Example: get text programmatically
//!
//! ```rust
//! # use std::error::Error;
//! #
//! use skyscraper::html;
//! use skyscraper::xpath;
//!
//! # fn main() -> Result<(), Box<dyn Error>> {
//! let text = r##"
//! <html>
//!     <body>
//!         <div>Example 1</div>
//!         <div>Example 2</div>
//!     </body>
//! </html>"##;
//!
//! // Parse the HTML text
//! let xpath_item_tree = html::parse(text)?;
//!
//! let xpath = xpath::parse("//div")?;
//!
//! // Apply the XPath expression to our HTML document
//! let items = xpath.apply(&xpath_item_tree)?;
//!
//! let text_contents: Vec<String> = items
//!     .iter()
//!     .map(|item| item
//!         .extract_as_node() // we know it's a node because text is type of node
//!         .extract_as_element_node() // we know it's an element node
//!         .text_content(&xpath_item_tree)
//!     )
//!     .collect();
//!
//! assert_eq!(text_contents, vec!["Example 1", "Example 2"]);
//!
//! # Ok(())
//! # }
//! ```

use std::rc::Rc;

use thiserror::Error;

use self::{
    grammar::{data_model::XpathItem, xpath},
    xpath_item_set::XpathItemSet,
};

pub mod grammar;
pub mod query;
pub mod xpath_item_set;

pub use self::grammar::{Xpath, XpathItemTree};

/// Error that occurs when parsing an [Xpath] expression.
#[derive(PartialEq, Debug, Error)]
#[error("Error parsing expression: {msg}")]
pub struct ExpressionParseError {
    msg: String,
}

/// Parse a string into an [Xpath] expression.
///
/// # Example
///
/// ```rust
/// use skyscraper::xpath::parse;
///
/// let xpath = parse("//div[@class='yes']/parent::div/div[@class='duplicate']")
///    .expect("xpath is invalid");
/// ```
pub fn parse(input: &str) -> Result<Xpath, ExpressionParseError> {
    let (remaining, parsed) = xpath(input).map_err(|e| ExpressionParseError {
        msg: format!("{}", e),
    })?;
    if !remaining.trim().is_empty() {
        return Err(ExpressionParseError {
            msg: format!("unexpected trailing input: {:?}", remaining),
        });
    }
    Ok(parsed)
}

/// Error that occurs when applying an [Xpath] expression to an [XpathItemTree].
#[derive(PartialEq, Debug, Error)]
#[error("Error applying expression {msg}")]
pub struct ExpressionApplyError {
    msg: String,
}

impl ExpressionApplyError {
    pub(crate) fn new(msg: String) -> Self {
        Self { msg }
    }
}

/// A scope-chain node for variable bindings.
///
/// Each node holds a small set of bindings and an optional parent pointer.
/// Lookup walks the chain (O(depth), typically <10).
#[derive(Debug)]
pub(crate) struct VariableScope<'tree> {
    bindings: Vec<(String, XpathItemSet<'tree>)>,
    parent: Option<Rc<VariableScope<'tree>>>,
}

impl<'tree> VariableScope<'tree> {
    fn empty() -> Self {
        Self {
            bindings: Vec::new(),
            parent: None,
        }
    }

    fn get(&self, name: &str) -> Option<&XpathItemSet<'tree>> {
        for (k, v) in self.bindings.iter().rev() {
            if k == name {
                return Some(v);
            }
        }
        if let Some(parent) = &self.parent {
            parent.get(name)
        } else {
            None
        }
    }
}

#[derive(Debug)]
pub(crate) struct XpathExpressionContext<'tree> {
    item_tree: &'tree XpathItemTree,
    item: XpathItem<'tree>,
    position: usize,

    size: usize,

    /// `true` if this is the initial step of a path expression evaluation;
    /// `false` for subsequent steps within a relative path.
    ///
    /// This determines how leading `/` and `//` are expanded.
    is_initial_step: bool,

    /// Variable bindings in scope (e.g. from `for` or `let` expressions).
    /// Uses a scope-chain so that adding a variable is O(1) instead of O(n).
    variables: Rc<VariableScope<'tree>>,
}

impl<'tree> XpathExpressionContext<'tree> {
    pub fn new_single(
        item_tree: &'tree XpathItemTree,
        item: XpathItem<'tree>,
        is_initial_step: bool,
    ) -> Self {
        Self {
            item_tree,
            item,
            position: 1,
            size: 1,
            is_initial_step,
            variables: Rc::new(VariableScope::empty()),
        }
    }

    /// Create a new context that inherits variable bindings from this context,
    /// with a new item and position derived from an item set.
    pub fn new_with_variables(
        &self,
        items: &XpathItemSet<'tree>,
        position: usize,
        is_initial_step: bool,
    ) -> Self {
        debug_assert!(position > 0, "XPath position is 1-based, got 0");
        debug_assert!(
            position <= items.len(),
            "position {} exceeds items length {}",
            position,
            items.len()
        );
        Self {
            item_tree: self.item_tree,
            item: items[position - 1].clone(),
            position,
            size: items.len(),
            is_initial_step,
            variables: Rc::clone(&self.variables),
        }
    }

    /// Create a new context that inherits variable bindings from this context,
    /// with a directly specified item, position, and size.
    ///
    /// This avoids the need to create an intermediate `XpathItemSet` when the
    /// item and positional information are already known (e.g., during grouped
    /// descendant predicate evaluation).
    pub fn new_with_item_and_size(
        &self,
        item: XpathItem<'tree>,
        position: usize,
        size: usize,
        is_initial_step: bool,
    ) -> Self {
        Self {
            item_tree: self.item_tree,
            item,
            position,
            size,
            is_initial_step,
            variables: Rc::clone(&self.variables),
        }
    }

    /// Create a new context with an additional variable binding.
    /// Inherits all existing variables plus the new one.
    pub fn with_variable(
        &self,
        name: String,
        value: XpathItemSet<'tree>,
    ) -> Self {
        Self {
            item_tree: self.item_tree,
            item: self.item.clone(),
            position: self.position,
            size: self.size,
            is_initial_step: self.is_initial_step,
            variables: Rc::new(VariableScope {
                bindings: vec![(name, value)],
                parent: Some(Rc::clone(&self.variables)),
            }),
        }
    }

    /// Look up a variable binding by name.
    pub fn get_variable(&self, name: &str) -> Option<&XpathItemSet<'tree>> {
        self.variables.get(name)
    }

    /// Create a new context with multiple additional variable bindings.
    pub fn with_variables_iter(
        &self,
        bindings: impl IntoIterator<Item = (String, XpathItemSet<'tree>)>,
    ) -> Self {
        Self {
            item_tree: self.item_tree,
            item: self.item.clone(),
            position: self.position,
            size: self.size,
            is_initial_step: self.is_initial_step,
            variables: Rc::new(VariableScope {
                bindings: bindings.into_iter().collect(),
                parent: Some(Rc::clone(&self.variables)),
            }),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn parse_should_handle_multiple_double_slashes() {
        // arrange
        let xpath_text = r###"//hello//world"###;

        // act
        let xpath = parse(xpath_text).unwrap();

        // assert
        assert_eq!(xpath.to_string(), xpath_text);
    }

    #[test]
    fn parse_should_handle_reverse_step_after_double_slash() {
        // arrange
        let xpath_text = r###"//hello//parent::world"###;

        // act
        let xpath = parse(xpath_text).unwrap();

        // assert
        assert_eq!(xpath.to_string(), xpath_text);
    }
}