diff --git a/src/lib.rs b/src/lib.rs index 2cdd4d2..1a68a61 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -15,13 +15,18 @@ mod tests {

hello world

good bye

+ simple text -"; +" + .to_string(); let sel = Selector::from_html(html); - println!("{:?}", sel.css("h1")); - assert_eq!(sel.css("h1")[0].html(), "

hello world

"); - assert_eq!(sel.css("#text")[0].content(), "good bye"); + assert_eq!(sel.css::("h1")[0].html(), "

hello world

"); + assert_eq!(sel.css::("#text")[0].content(), "good bye"); + assert_eq!( + sel.css_once::("body > a").unwrap().content(), + "simple text" + ); } #[test] @@ -29,6 +34,6 @@ mod tests { let req: Request = RequestBase::new("https://httpbin.org/"); let resp = req.launch(); assert_eq!(resp.status_code, StatusCode::OK); - assert!(resp.css("h2")[0].html().contains("httpbin.org")); + assert!(resp.css::("h2")[0].html().contains("httpbin.org")); } } diff --git a/src/response.rs b/src/response.rs index 0bfc9d2..be5ea7e 100644 --- a/src/response.rs +++ b/src/response.rs @@ -10,7 +10,11 @@ pub struct Response { } impl SelectorBase for Response { - fn html(&self) -> &str { - self.text.as_str() + fn from_html(_: String) -> Self { + panic!("Not implemented") + } + + fn html(&self) -> String { + format!("{}", self.text) } } diff --git a/src/selector.rs b/src/selector.rs index 94ec37c..7b40b02 100644 --- a/src/selector.rs +++ b/src/selector.rs @@ -1,19 +1,25 @@ pub trait SelectorBase { - fn html(&self) -> &str; + fn from_html(html: String) -> Self; - fn css(&self, css_selector: &'static str) -> Vec { - let html = nipper::Document::from(self.html()); - html.select(css_selector) - .iter() - .map(|element| Selector { - text: element.html().to_string(), - }) - .into_iter() - .collect::>() + fn html(&self) -> String; + + fn css(&self, css_selector: &'static str) -> Vec { + 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(&self, css_selector: &'static str) -> Option { + self.css(css_selector).pop() } fn content(&self) -> String { - let html = nipper::Document::from(self.html()); + let html = nipper::Document::from(self.html().as_str()); html.select("*") .iter() .map(|element| element.text().to_string()) @@ -28,15 +34,13 @@ pub struct Selector { } impl SelectorBase for Selector { - fn html(&self) -> &str { - self.text.as_str() - } -} - -impl Selector { - pub fn from_html(html: &'static str) -> Self { + fn from_html(html: String) -> Self { Selector { text: html.to_string(), } } + + fn html(&self) -> String { + format!("{}", self.text) + } }