2 个版本
0.17.2-rc | 2023 年 10 月 6 日 |
---|---|
0.17.1 | 2023 年 10 月 5 日 |
2351 在 Web 编程
用于 victor_tree
67KB
1.5K SLoC
scraper
使用 CSS 选择器进行 HTML 解析和查询。
scraper
在 Crates.io 和 GitHub 上。
Scraper 提供了一个接口,用于 Servo 的 html5ever
和 selectors
crate,用于浏览器级解析和查询。
示例
解析文档
use scraper::Html;
let html = r#"
<!DOCTYPE html>
<meta charset="utf-8">
<title>Hello, world!</title>
<h1 class="foo">Hello, <i>world!</i></h1>
"#;
let document = Html::parse_document(html);
解析片段
use scraper::Html;
let fragment = Html::parse_fragment("<h1>Hello, <i>world!</i></h1>");
解析选择器
use scraper::Selector;
let selector = Selector::parse("h1.foo").unwrap();
选择元素
use scraper::{Html, Selector};
let html = r#"
<ul>
<li>Foo</li>
<li>Bar</li>
<li>Baz</li>
</ul>
"#;
let fragment = Html::parse_fragment(html);
let selector = Selector::parse("li").unwrap();
for element in fragment.select(&selector) {
assert_eq!("li", element.value().name());
}
选择后代元素
use scraper::{Html, Selector};
let html = r#"
<ul>
<li>Foo</li>
<li>Bar</li>
<li>Baz</li>
</ul>
"#;
let fragment = Html::parse_fragment(html);
let ul_selector = Selector::parse("ul").unwrap();
let li_selector = Selector::parse("li").unwrap();
let ul = fragment.select(&ul_selector).next().unwrap();
for element in ul.select(&li_selector) {
assert_eq!("li", element.value().name());
}
访问元素属性
use scraper::{Html, Selector};
let fragment = Html::parse_fragment(r#"<input name="foo" value="bar">"#);
let selector = Selector::parse(r#"input[name="foo"]"#).unwrap();
let input = fragment.select(&selector).next().unwrap();
assert_eq!(Some("bar"), input.value().attr("value"));
序列化 HTML 和内部 HTML
use scraper::{Html, Selector};
let fragment = Html::parse_fragment("<h1>Hello, <i>world!</i></h1>");
let selector = Selector::parse("h1").unwrap();
let h1 = fragment.select(&selector).next().unwrap();
assert_eq!("<h1>Hello, <i>world!</i></h1>", h1.html());
assert_eq!("Hello, <i>world!</i>", h1.inner_html());
访问后代文本
use scraper::{Html, Selector};
let fragment = Html::parse_fragment("<h1>Hello, <i>world!</i></h1>");
let selector = Selector::parse("h1").unwrap();
let h1 = fragment.select(&selector).next().unwrap();
let text = h1.text().collect::<Vec<_>>();
assert_eq!(vec!["Hello, ", "world!"], text);
操作 DOM
use html5ever::tree_builder::TreeSink;
use scraper::{Html, Selector};
let html = "<html><body>hello<p class=\"hello\">REMOVE ME</p></body></html>";
let selector = Selector::parse(".hello").unwrap();
let mut document = Html::parse_document(html);
let node_ids: Vec<_> = document.select(&selector).map(|x| x.id()).collect();
for id in node_ids {
document.remove_from_parent(&id);
}
assert_eq!(document.html(), "<html><head></head><body>hello</body></html>");
贡献
请随时打开 pull request。如果您计划实现一些大的功能(即不是修复错别字、小错误修复、微小重构等),那么请首先打开一个问题。
依赖关系
~4–10MB
~101K SLoC