modify the css method to able a more flexible environment

master
kirbylife 2021-01-25 20:52:39 -06:00
parent 78bd9af763
commit b77d4959ea
3 changed files with 38 additions and 25 deletions

View File

@ -15,13 +15,18 @@ mod tests {
<body>
<h1>hello world</h1>
<p id='text'>good bye</p>
<a>simple text</a>
</body>
</html>
";
"
.to_string();
let sel = Selector::from_html(html);
println!("{:?}", sel.css("h1"));
assert_eq!(sel.css("h1")[0].html(), "<h1>hello world</h1>");
assert_eq!(sel.css("#text")[0].content(), "good bye");
assert_eq!(sel.css::<Selector>("h1")[0].html(), "<h1>hello world</h1>");
assert_eq!(sel.css::<Selector>("#text")[0].content(), "good bye");
assert_eq!(
sel.css_once::<Selector>("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::<Selector>("h2")[0].html().contains("httpbin.org"));
}
}

View File

@ -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)
}
}

View File

@ -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<Selector> {
let html = nipper::Document::from(self.html());
html.select(css_selector)
.iter()
.map(|element| Selector {
text: element.html().to_string(),
})
.into_iter()
.collect::<Vec<_>>()
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()
}
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)
}
}