2021-01-18 02:01:06 +00:00
|
|
|
pub trait SelectorBase {
|
2021-01-26 02:52:39 +00:00
|
|
|
fn from_html(html: String) -> Self;
|
2021-01-18 02:01:06 +00:00
|
|
|
|
2021-01-26 02:52:39 +00:00
|
|
|
fn html(&self) -> String;
|
|
|
|
|
|
|
|
fn css<T: SelectorBase>(&self, css_selector: &'static str) -> Vec<T> {
|
|
|
|
let html = nipper::Document::from(self.html().as_str());
|
|
|
|
|
|
|
|
let mut output = vec![];
|
|
|
|
|
|
|
|
for item in html.select(css_selector).iter() {
|
|
|
|
output.push(T::from_html(item.html().to_string()))
|
|
|
|
}
|
|
|
|
output
|
|
|
|
}
|
|
|
|
|
|
|
|
fn css_once<T: SelectorBase>(&self, css_selector: &'static str) -> Option<T> {
|
|
|
|
self.css(css_selector).pop()
|
2021-01-18 02:01:06 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
fn content(&self) -> String {
|
2021-01-26 02:52:39 +00:00
|
|
|
let html = nipper::Document::from(self.html().as_str());
|
2021-01-31 03:11:54 +00:00
|
|
|
html.select("body > *")
|
2021-01-18 02:01:06 +00:00
|
|
|
.iter()
|
|
|
|
.map(|element| element.text().to_string())
|
|
|
|
.last()
|
|
|
|
.unwrap()
|
|
|
|
}
|
2021-01-31 03:11:54 +00:00
|
|
|
|
|
|
|
fn attr(&self, attribute: &'static str) -> Option<String> {
|
|
|
|
let html = nipper::Document::from(self.html().as_str());
|
|
|
|
match html.select("body > *").attr(attribute) {
|
|
|
|
Some(text) => Some(format!("{}", text)),
|
|
|
|
None => None,
|
|
|
|
}
|
|
|
|
}
|
2021-01-18 02:01:06 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
#[derive(Debug)]
|
|
|
|
pub struct Selector {
|
|
|
|
text: String,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl SelectorBase for Selector {
|
2021-01-26 02:52:39 +00:00
|
|
|
fn from_html(html: String) -> Self {
|
2021-01-18 02:01:06 +00:00
|
|
|
Selector {
|
|
|
|
text: html.to_string(),
|
|
|
|
}
|
|
|
|
}
|
2021-01-26 02:52:39 +00:00
|
|
|
|
|
|
|
fn html(&self) -> String {
|
|
|
|
format!("{}", self.text)
|
|
|
|
}
|
2021-01-18 02:01:06 +00:00
|
|
|
}
|