Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
66 changes: 35 additions & 31 deletions examples/html-py-ever/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion examples/html-py-ever/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ authors = ["konstin <konstin@mailbox.org>"]
edition = "2021"

[dependencies]
scraper = "0.27"
scraper = { version = "0.29", features = ["atomic"] }
pyo3 = "0.29.3"

[lib]
Expand Down
30 changes: 20 additions & 10 deletions examples/html-py-ever/rust/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,24 +7,30 @@ mod html_py_ever {
use std::fs;
use std::io::Read;
use std::path::Path;
use std::sync::Mutex;

/// A parsed html document
#[pyclass(unsendable)]
#[pyclass]
struct Document {
html: Html,
// NB a top-level mutex may not be appropriate for all applications; this is
// a simple example and you should consider your own concurrency model for your application.
html: Mutex<Html>,
}

#[pymethods]
impl Document {
/// Returns the selected elements as strings
fn select(&self, selector: &str) -> PyResult<Vec<String>> {
fn select(&self, py: Python<'_>, selector: &str) -> PyResult<Vec<String>> {
let selector = Selector::parse(selector)
.map_err(|e| PyErr::new::<pyo3::exceptions::PyValueError, _>(format!("{e:?}")))?;
Ok(self
.html
.select(&selector)
.map(|element| element.html())
.collect())
py.detach(|| {
let html = self.html.lock().unwrap();
let elements: Vec<String> = html
.select(&selector)
.map(|element| element.html())
.collect();
Ok(elements)
})
}
}

Expand All @@ -33,13 +39,17 @@ mod html_py_ever {
let mut html_string = String::new();
reader.read_to_string(&mut html_string)?;
let html = Html::parse_document(&html_string);
Ok(Document { html })
Ok(Document {
html: Mutex::new(html),
})
}

fn from_file(path: &Path) -> PyResult<Document> {
let html_string = fs::read_to_string(path)?;
let html = Html::parse_document(&html_string);
Ok(Document { html })
Ok(Document {
html: Mutex::new(html),
})
}
}

Expand Down
Loading