Debian Codegraph @

examples/html-py-ever/rust/lib.rs

raw
1 use pyo3::prelude::*;
2
3 #[pymodule]
4 mod html_py_ever {
5 use pyo3::prelude::*;
6 use std::io::Read;
7 use std::path::Path;
8 use tendril::stream::TendrilSink;
9
10 /// A parsed html document
11 #[pyclass(unsendable)]
12 struct Document {
13 node: kuchiki::NodeRef,
14 }
15
16 #[pymethods]
17 impl Document {
18 /// Returns the selected elements as strings
19 fn select(&self, selector: &str) -> Vec<String> {
20 self.node
21 .select(selector)
22 .unwrap()
23 .map(|css_match| css_match.text_contents())
24 .collect()
25 }
26 }
27
28 impl Document {
29 fn from_reader(reader: &mut impl Read) -> PyResult<Document> {
30 let node = kuchiki::parse_html().from_utf8().read_from(reader)?;
31 Ok(Document { node })
32 }
33
34 fn from_file(path: &Path) -> PyResult<Document> {
35 let node = kuchiki::parse_html().from_utf8().from_file(path)?;
36 Ok(Document { node })
37 }
38 }
39
40 /// Parses the File from the specified Path into a document
41 #[pyfunction]
42 fn parse_file(path: &str) -> PyResult<Document> {
43 let document = Document::from_file(Path::new(path))?;
44 Ok(document)
45 }
46
47 /// Parses the given html test into a document
48 #[pyfunction]
49 fn parse_text(text: &str) -> PyResult<Document> {
50 let document = Document::from_reader(&mut text.as_bytes())?;
51 Ok(document)
52 }
53 }