scrapelect 0.3.2

Interpreter for scrapelect, a CSS-inspired web scraping DSL
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
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
use std::{borrow::Cow, collections::BTreeMap, sync::Arc};

use anyhow::Context;
use execution_mode::ExecutionMode;
use reqwest::Url;

use value::{EValue, ListIter, PValue};

use crate::frontend::{
    ast::{
        self, AstRef, Element, FilterList, Inline, Leaf, Qualifier, RValue, Statement,
        StatementList,
    },
    AstArena,
};

mod execution_mode;
pub mod filter;
pub mod value;

pub use filter::{Filter, FilterDyn};
pub use value::Value;

pub type Error = anyhow::Error;
pub type Result<T> = core::result::Result<T, Error>;

impl<'ast> Element<'ast> {
    #[must_use]
    pub fn to_selector_str(&self, ast: &AstArena<'ast>) -> String {
        use std::fmt::Write as _;

        let mut buf = String::new();
        let _ = write!(&mut buf, "{}", self.selector_head);

        for selector in ast.flatten(self.selectors) {
            let _ = write!(&mut buf, "{}", selector.sel);
        }

        buf
    }
}

#[derive(Debug, Default)]
pub struct Variables<'a, 'b>(pub BTreeMap<Cow<'a, str>, EValue<'b>>);

#[derive(Debug, Default)]
pub struct DataVariables<'a>(pub BTreeMap<Cow<'a, str>, Value>);

impl<'a, 'b> From<Variables<'a, 'b>> for DataVariables<'a> {
    fn from(value: Variables<'a, 'b>) -> Self {
        Self(
            value
                .0
                .into_iter()
                .filter_map(|(k, v)| v.into_data().map(|v| (k, v)))
                .collect(),
        )
    }
}

impl<'a, 'b> From<DataVariables<'a>> for Variables<'a, 'b> {
    fn from(value: DataVariables<'a>) -> Self {
        Self(
            value
                .0
                .into_iter()
                .map(|(k, v)| (k, Value::from_data(v)))
                .collect(),
        )
    }
}

impl<'ast> From<DataVariables<'ast>> for Value {
    fn from(value: DataVariables<'ast>) -> Self {
        Self::Structure(
            value
                .0
                .into_iter()
                .map(|(k, v)| (Arc::from(&*k), v))
                .collect(),
        )
    }
}

#[derive(Debug)]
pub struct ElementContext<'ast, 'ctx> {
    variables: Variables<'ast, 'ctx>,
    element: scraper::ElementRef<'ctx>,
    parent: Option<&'ctx ElementContext<'ast, 'ctx>>,
    url: Url,
}

#[derive(Debug)]
pub struct Interpreter<'ast> {
    client: reqwest::Client,
    ast: &'ast AstArena<'ast>,
}

impl<'ast> Interpreter<'ast> {
    #[must_use]
    #[inline]
    pub fn new(ast: &'ast AstArena<'ast>) -> Self {
        Self::with_client(
            ast,
            reqwest::Client::builder()
                .user_agent(concat!(
                    env!("CARGO_PKG_NAME"),
                    " v",
                    env!("CARGO_PKG_VERSION")
                ))
                .build()
                .expect("Default client is invalid"),
        )
    }

    #[must_use]
    #[inline]
    pub const fn with_client(ast: &'ast AstArena<'ast>, client: reqwest::Client) -> Self {
        Self { ast, client }
    }

    #[inline]
    pub async fn interpret(
        &self,
        root_url: Url,
        head: Option<AstRef<'ast, StatementList<'ast>>>,
    ) -> Result<DataVariables<'ast>> {
        let html = self.get_html(&root_url).await?;
        self.interpret_block(html.root_element(), head, None, root_url)
            .await
    }

    async fn get_html(&self, url: &Url) -> Result<scraper::Html> {
        let text = match url.scheme() {
            "http" | "https" => self
                .client
                .get(url.clone())
                .send()
                .await
                .context("Error sending HTTP request")?
                .text()
                .await
                .context("Error getting HTTP body text")?,
            "file" => tokio::fs::read_to_string(url.path())
                .await
                .with_context(|| format!("Error reading from file `{}`", url.path()))?,
            other => anyhow::bail!("unknown URL scheme `{other}`"),
        };

        Ok(scraper::Html::parse_document(&text))
    }

    async fn interpret_block(
        &self,
        element: scraper::ElementRef<'_>,
        statements: Option<AstRef<'ast, StatementList<'ast>>>,
        parent: Option<&ElementContext<'ast, '_>>,
        url: Url,
    ) -> Result<DataVariables<'ast>> {
        let mut ctx = ElementContext {
            element,
            parent,
            variables: Variables::default(),
            url,
        };

        for statement in self.ast.flatten(statements) {
            self.interpret_statement(&statement.value, &mut ctx).await?;
        }

        Ok(ctx.variables.into())
    }

    async fn interpret_statement(
        &self,
        statement: &Statement<'ast>,
        ctx: &mut ElementContext<'ast, '_>,
    ) -> Result<()> {
        let value = match &statement.value {
            RValue::Leaf(l) => ctx.leaf_to_value(l)?,
            RValue::Element(e) => Value::from_data(self.interpret_element(e, ctx).await?),
        };

        let value =
            self.apply_filters(value, self.ast.flatten(statement.filters).into_iter(), ctx)?;
        ctx.set_var(Cow::Borrowed(statement.id), value)?;

        Ok(())
    }

    async fn interpret_element(
        &self,
        element: &Element<'ast>,
        ctx: &mut ElementContext<'ast, '_>,
    ) -> anyhow::Result<Value> {
        let html;

        let (root_element, url) = if let Some(url) = &element.url {
            let url: Arc<str> = self.eval_inline(url, ctx)?.try_unwrap()?;
            let url: Url = match url.parse() {
                Ok(url) => url,
                Err(url::ParseError::RelativeUrlWithoutBase) => ctx
                    .url
                    .join(&url)
                    .with_context(|| format!("`{url} is not a valid relative URL"))?,
                Err(e) => anyhow::bail!("`{url}` is not a valid URL: {e}"),
            };
            html = self.get_html(&url).await?;
            (html.root_element(), url)
        } else {
            (ctx.element, ctx.url.clone())
        };

        let selector_str = element.to_selector_str(self.ast);

        let selector = scraper::Selector::parse(&selector_str).map_err(|e| {
            anyhow::anyhow!(
                "Selector parse failed: {e}.  This is a program error. Selector is `{selector_str}`",
            )
        })?;

        let selection = root_element.select(&selector);

        let element_refs = ExecutionMode::hinted_from_iter(element.qualifier, selection)?;

        let values = futures::future::try_join_all(element_refs.into_iter().map(|element_ref| {
            self.interpret_block(element_ref, element.statements, Some(ctx), url.clone())
        }))
        .await?;

        Ok(
            ExecutionMode::hinted_from_iter(
                element.qualifier,
                values.into_iter().map(Value::from),
            )?
            .into_value(),
        )
    }

    fn apply_filters<'ctx>(
        &self,
        value: EValue<'ctx>,
        mut filters: impl Iterator<Item = &'ast FilterList<'ast>>,
        ctx: &mut ElementContext<'ast, 'ctx>,
    ) -> Result<EValue<'ctx>> {
        filters
            .try_fold(value.into(), |value, filter| match &filter.filter {
                ast::Filter::Call(call) => {
                    let args = self
                        .ast
                        .flatten(call.args)
                        .into_iter()
                        .map(|arg| Ok((arg.id, self.eval_inline(&arg.value, ctx)?)))
                        .collect::<Result<BTreeMap<_, _>>>()?;
                    qualify(filter.qualifier, value, |value| {
                        filter::dispatch_filter(call.id, value, args.clone(), ctx)
                    })
                }
                ast::Filter::Select(select) => qualify(filter.qualifier, value, |value| {
                    let ls: ListIter = value.try_unwrap()?;

                    let mut inner_scope = ElementContext {
                        element: ctx.element,
                        variables: Variables::default(),
                        parent: Some(ctx),
                        url: ctx.url.clone(),
                    };

                    Ok(Value::List(
                        ls.map(|value| {
                            let value = EValue::from(value);
                            inner_scope.set_var(select.name.into(), value.clone())?;

                            let keep: bool = self
                                .eval_inline(&select.value, &mut inner_scope)?
                                .try_unwrap()?;

                            Ok(keep.then(|| value.into()))
                        })
                        .filter_map(Result::transpose)
                        .collect::<Result<_>>()?,
                    ))
                }),
            })
            .map(EValue::from)
    }

    fn eval_inline<'ctx>(
        &self,
        inline: &Inline<'ast>,
        ctx: &mut ElementContext<'ast, 'ctx>,
    ) -> Result<EValue<'ctx>> {
        self.apply_filters(
            ctx.leaf_to_value(&inline.value)?,
            self.ast.flatten(inline.filters).into_iter(),
            ctx,
        )
    }
}

fn qualify<'doc, F>(
    qualifier: Qualifier,
    value: PValue<'doc>,
    mut action: F,
) -> Result<PValue<'doc>>
where
    F: FnMut(PValue<'doc>) -> Result<PValue<'doc>>,
{
    match qualifier {
        Qualifier::One => action(value),
        Qualifier::Optional if matches!(value, Value::Null) => Ok(Value::Null),
        Qualifier::Optional => action(value),
        Qualifier::Collection => value
            .try_unwrap::<ListIter>()?
            .map(action)
            .collect::<Result<Vec<_>>>()
            .map(Value::List),
    }
}

impl<'ast, 'ctx> ElementContext<'ast, 'ctx> {
    pub fn get_var(&self, id: &str) -> anyhow::Result<EValue<'ctx>> {
        match id {
            "element" => Ok(self.element.into()),
            var => match self.variables.0.get(var) {
                Some(var) => Ok(var.clone()),
                None => self
                    .parent
                    .with_context(|| format!("Unknown variable `{var}`"))?
                    .get_var(id),
            },
        }
    }

    pub fn set_var(&mut self, name: Cow<'ast, str>, value: EValue<'ctx>) -> anyhow::Result<()> {
        match &*name {
            immutable @ "element" => {
                anyhow::bail!("Can't assign to immutable variable `{immutable}`")
            }
            _ => self.variables.0.insert(name, value),
        };

        Ok(())
    }

    pub fn leaf_to_value(&self, value: &Leaf<'ast>) -> anyhow::Result<EValue<'ctx>> {
        match value {
            Leaf::Float(x) => Ok(Value::Float(*x)),
            Leaf::Int(n) => Ok(Value::Int(*n)),
            Leaf::String(s) => Ok(Value::String(Arc::from(&**s))),
            Leaf::Var(id) => self.get_var(id),
        }
    }
}

#[cfg(test)]
pub async fn interpret_string_harness(
    program: &'static str,
    html: &'static str,
) -> Result<DataVariables<'static>> {
    let (ast, head) = crate::frontend::Parser::new(program).parse()?;
    let html = scraper::Html::parse_document(html);
    let interpreter = Interpreter::new(Box::leak(Box::new(ast)));
    interpreter
        // TODO: url hack
        .interpret_block(
            html.root_element(),
            head,
            None,
            "file:///tmp/inmemory.html".parse().expect("URL parse"),
        )
        .await
}

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

    async fn integration_test(filename: &str) -> anyhow::Result<()> {
        let input = std::fs::read_to_string(format!("examples/inputs/{filename}.html"))?;
        let script = std::fs::read_to_string(format!("examples/scrps/{filename}.scrp"))?;

        let (ast, head) = crate::frontend::Parser::new(&script)
            .parse()
            .expect("parse error");

        let html = scraper::Html::parse_document(&input);

        let result = super::Interpreter::new(&ast)
            .interpret_block(
                html.root_element(),
                head,
                None,
                format!(
                    "file://{}/examples/inputs/{}",
                    std::env::current_dir().expect("get current dir").display(),
                    filename,
                )
                .parse()
                .expect("parse URL failed"),
            )
            .await?
            .0;

        let mut settings = insta::Settings::clone_current();
        settings.set_snapshot_path("../../examples/outputs");
        settings.set_prepend_module_to_snapshot(false);

        settings.bind(|| {
            insta::assert_json_snapshot!(filename, result);
        });

        Ok(())
    }

    macro_rules! integration_test {
        {
            $($name: ident,)*
        } => {
            $(
                #[tokio::test]
                async fn $name() -> anyhow::Result<()> {
                    integration_test(stringify!($name)).await
                }
            )*
        };
    }

    #[tokio::test]
    async fn test_basic() {
        let output = super::interpret_string_harness(
            r#"
            h3: h3 {
                text: $element | text();

                a: a {
                    child: $element | text();
                    parent: $text;
                }*;
                div: div {}?;
            };
            "#,
            r#"
                <html>
                    <h3>Hello,<a>Hello, child</a><span></span>parent!</h3>
                </html>
            "#,
        )
        .await
        .expect("parsing and interpreting should succeed");

        let Some(Structure(d)) = output.0.get("h3") else {
            panic!("got {output:?}, expected h3: {{ .. }}")
        };

        let Some(List(a)) = d.get("a") else {
            panic!("got {output:?}, expected a: [ .. ]");
        };

        let Some(Structure(a)) = a.get(0) else {
            panic!("got {output:?}");
        };

        assert!(
            match a.get("parent") {
                Some(String(x)) => &**x == "Hello,parent!",
                _ => false,
            },
            "got {output:?}"
        );

        assert!(
            match a.get("child") {
                Some(String(x)) => &**x == "Hello, child",
                _ => false,
            },
            "got {output:?}"
        );

        assert!(
            match d.get("text") {
                Some(String(x)) => &**x == "Hello,parent!",
                _ => false,
            },
            "got {output:?}"
        );
    }

    integration_test! {
        abc,
        attr,
        qualifiers,
        relative,
        recurser,
        filter_select,
    }
}