html_helpers/
elem.rs

1use serde::Serialize;
2use std::collections::HashMap;
3
4/// Represents a simplified HTML element, suitable for serialization.
5#[derive(Debug, Serialize)]
6pub struct Elem {
7	pub tag: String,
8	pub attrs: Option<HashMap<String, String>>,
9	pub text: Option<String>,
10	pub inner_html: Option<String>,
11}
12
13impl Elem {
14	/// Creates a new `Elem` from a `scraper::ElementRef`.
15	pub(crate) fn from_element_ref(el_ref: scraper::ElementRef) -> Self {
16		let el = el_ref.value();
17		let tag = el.name().to_string();
18
19		let attrs = if el.attrs().next().is_some() {
20			let attrs = el.attrs().map(|(k, v)| (k.to_string(), v.to_string())).collect();
21			Some(attrs)
22		} else {
23			None
24		};
25
26		let full_text = el_ref.text().collect::<String>();
27		let text = if full_text.trim().is_empty() {
28			None
29		} else {
30			Some(full_text.to_string())
31		};
32
33		let html_content = el_ref.inner_html();
34		let inner_html = if html_content.trim().is_empty() {
35			None
36		} else {
37			Some(html_content.to_string())
38		};
39
40		Elem {
41			tag,
42			attrs,
43			text,
44			inner_html,
45		}
46	}
47}