Expand description
Inspired by the Python library “BeautifulSoup,” soup
is a layer on top of
html5ever
that aims to provide a slightly different API for querying &
manipulating HTML
Examples (inspired by bs4’s docs)
const THREE_SISTERS: &'static str = r#"
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title"><b>The Dormouse's story</b></p>
<p class="story">Once upon a time there were three little sisters; and their names were
<a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>,
<a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
<a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;
and they lived at the bottom of a well.</p>
<p class="story">...</p>
"#;
let soup = Soup::new(THREE_SISTERS);
let title = soup.tag("title").find().unwrap();
assert_eq!(title.display(), "<title>The Dormouse's story</title>");
assert_eq!(title.name(), "title");
assert_eq!(title.text(), "The Dormouse's story".to_string());
let p = soup.tag("p").find().unwrap();
assert_eq!(
p.display(),
r#"<p class="title"><b>The Dormouse's story</b></p>"#
);
assert_eq!(p.get("class"), Some("title".to_string()));
let a = soup.tag("a").find().unwrap();
assert_eq!(
a.display(),
r#"<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>"#
);
let a_s = soup.tag("a").find_all().collect::<Vec<_>>();
assert_eq!(
a_s.iter()
.map(|a| a.display())
.collect::<Vec<_>>()
.join("\n"),
r#"<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>
<a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>
<a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>"#
);
let expected = [
"http://example.com/elsie",
"http://example.com/lacie",
"http://example.com/tillie",
];
for (i, link) in soup.tag("a").find_all().enumerate() {
let href = link.get("href").unwrap();
assert_eq!(href, expected[i].to_string());
}
let text = soup.text();
assert_eq!(
text,
r#"The Dormouse's story
The Dormouse's story
Once upon a time there were three little sisters; and their names were
Elsie,
Lacie and
Tillie;
and they lived at the bottom of a well.
...
"#
);
You can use more than just strings to search for results:
use regex::Regex;
let soup = Soup::new(r#"<body><p>some text, <b>Some bold text</b></p></body>"#);
let results = soup.tag(Regex::new("^b")?)
.find_all()
.map(|tag| tag.name().to_string())
.collect::<Vec<_>>();
assert_eq!(results, vec!["body".to_string(), "b".to_string()]);
Modules
Traits & impls for matching types with strings
This module exports all the important types & traits to use
soup
effectivelyStructs
Construct a query to apply to an HTML tree
Parses HTML & provides methods to query & manipulate the document