Now the selectors methods (css/_once, xpath/_once) works with str & String

master
kirbylife 2021-03-21 01:32:43 -06:00
parent f1c0bc340e
commit ded3cc4074
2 changed files with 13 additions and 15 deletions

View File

@ -14,4 +14,4 @@ http = "0.2"
nipper = "0.1.8" nipper = "0.1.8"
serde_json = "1.0" serde_json = "1.0"
serde = "1.0" serde = "1.0"
cssifier = "0.1.2" cssifier = "0.1.3"

View File

@ -3,26 +3,25 @@ pub trait SelectorBase {
fn html(&self) -> String; fn html(&self) -> String;
// fn css<'a, T: SelectorBase>(&self, css_selector: &'a str) -> Vec<T> { fn css<S: AsRef<str>>(&self, css_selector: S) -> Vec<Selector> {
fn css<'a>(&self, css_selector: &'a str) -> Vec<Selector> {
let html = nipper::Document::from(self.html().as_str()); let html = nipper::Document::from(self.html().as_str());
let mut output = vec![]; let mut output = vec![];
for item in html.select(css_selector).iter() { for item in html.select(css_selector.as_ref()).iter() {
output.push(Selector::from_html(item.html().to_string())) output.push(Selector::from_html(item.html().to_string()))
} }
output output
} }
fn css_once<'a>(&self, css_selector: &'a str) -> Option<Selector> { fn css_once<S: AsRef<str>>(&self, css_selector: S) -> Option<Selector> {
self.css(css_selector).pop() self.css(css_selector.as_ref()).pop()
} }
fn xpath(&self, xpath: &'static str) -> Vec<Selector> { fn xpath<S: AsRef<str>>(&self, xpath: S) -> Vec<Selector> {
match cssifier::cssifier(xpath) { match cssifier::cssifier(xpath.as_ref()) {
Some(css_selector) => { Some(css_selector) => {
if css_selector == "" { if css_selector.is_empty() {
Vec::default() Vec::default()
} else { } else {
self.css(css_selector.as_str()) self.css(css_selector.as_str())
@ -32,8 +31,8 @@ pub trait SelectorBase {
} }
} }
fn xpath_once(&self, xpath: &'static str) -> Option<Selector> { fn xpath_once<S: AsRef<str>>(&self, xpath: S) -> Option<Selector> {
self.xpath(xpath).pop() self.xpath(xpath.as_ref()).pop()
} }
fn content(&self) -> String { fn content(&self) -> String {
@ -47,10 +46,9 @@ pub trait SelectorBase {
fn attr<'a>(&self, attribute: &'a str) -> Option<String> { fn attr<'a>(&self, attribute: &'a str) -> Option<String> {
let html = nipper::Document::from(self.html().as_str()); let html = nipper::Document::from(self.html().as_str());
match html.select("body > *").attr(attribute) { html.select(" body > *")
Some(text) => Some(format!("{}", text)), .attr(attribute)
None => None, .map(|text| text.to_string())
}
} }
} }