9 个版本
新 0.3.2 | 2024 年 8 月 3 日 |
---|---|
0.3.1 | 2024 年 7 月 13 日 |
0.2.1 | 2024 年 7 月 9 日 |
0.1.3 | 2024 年 7 月 8 日 |
#7 在 #json-response
每月 397 次下载
26KB
399 行
reqwest-scraper - 使用 reqwest 进行网页抓取集成
扩展 reqwest 以支持多种网页抓取方法。
特性
入门指南
- 添加依赖
reqwest = { version = "0.12", features = ["json"] } reqwest-scraper="0.3.2"
- 使用 ScraperResponse
use reqwest_scraper::ScraperResponse;
JsonPath
Json::选择<T:DeserializeOwned>(路径: &str) -> 结果<Vec<T>>
Json::选择一个<T:DeserializeOwned>(路径: &str) -> 结果<T>
Json::选择为字符串(路径: &str) -> 结果<String>
示例:
use reqwest_scraper::ScraperResponse;
pub async fn request() -> Result<()> {
let json = reqwest::Client::builder()
.build()?
.get("https://api.github.com/search/repositories?q=rust")
.header("User-Agent", "Rust Reqwest")
.send()
.await?
.jsonpath()
.await?;
let total_count = json.select_as_str("$.total_count")?;
let names: Vec<String> = json.select("$.items[*].full_name")?;
println!("{}", total_count);
println!("{}", names.join("\t"));
Ok(())
}
CSS 选择器
Html::选择(选择器: &str) -> 结果<Selectable>
Selectable::迭代() ->实现迭代器<SelectItem>
Selectable::第一个() -> Option<SelectItem>
SelectItem::名称() -> &str
SelectItem::id() -> Option<&str>
SelectItem::有类(类: &str,大小写敏感:CaseSensitivity) -> bool
SelectItem::类() ->Classes
SelectItem::属性() ->Attrs
SelectItem::属性(属性: &str) -> Option<&str>
SelectItem::文本() ->String
SelectItem::html() ->String
SelectItem::内部_html() ->String
SelectItem::子元素() ->实现迭代器<SelectItem>
SelectItem::查找(选择器: &str) -> 结果<Selectable>
示例:
use reqwest_scraper::ScraperResponse;
async fn request() -> Result<()> {
let html = reqwest::get("https://github.com/holmofy")
.await?
.css_selector()
.await?;
assert_eq!(
html.select(".p-name")?.iter().nth(0).unwrap().text().trim(),
"holmofy"
);
let select_result = html.select(".vcard-details > li.vcard-detail")?;
for detail_item in select_result.iter() {
println!("{}", detail_item.attr("aria-label").unwrap())
}
Ok(())
}
XPath
XHtml::选择(xpath: &str) -> 结果<XPathResult>
XPathResult::as_nodes() -> Vec<Node>
XPathResult::as_strs() -> Vec<String>
XPathResult::as_node() -> Option<Node>
XPathResult::as_str() -> Option<String>
Node::名称() ->String
Node::id() -> Option<String>
Node::类() -> HashSet<String>
Node::属性(属性: &str) -> Option<String>
Node::有属性(属性: &str) -> bool
Node::文本() ->String
- TODO:
Node::html() -> String
- TODO:
Node::inner_html() -> String
Node::子元素() -> Vec<Node>
Node::findnodes(relative_xpath: &str) -> 结果<Vec<Node>>
Node::findvalues(relative_xpath: &str) -> 结果<Vec<String>>
Node::findnode(relative_xpath: &str) -> 结果<Option<Node>>
Node::findvalue(relative_xpath: &str) -> 结果<Option<String>>
示例:
async fn request() -> Result<()> {
let html = reqwest::get("https://github.com/holmofy")
.await?
.xpath()
.await?;
// simple extract element
let name = html
.select("//span[contains(@class,'p-name')]")?
.as_node()
.unwrap()
.text();
println!("{}", name);
assert_eq!(name.trim(), "holmofy");
// iterate elements
let select_result = html
.select("//ul[contains(@class,'vcard-details')]/li[contains(@class,'vcard-detail')]")?
.as_nodes();
println!("{}", select_result.len());
for item in select_result.into_iter() {
let attr = item.attr("aria-label").unwrap_or_else(|| "".into());
println!("{}", attr);
println!("{}", item.text());
}
// attribute extract
let select_result = html
.select("//ul[contains(@class,'vcard-details')]/li[contains(@class,'vcard-detail')]/@aria-label")?
.as_strs();
println!("{}", select_result.len());
select_result.into_iter().for_each(|s| println!("{}", s));
Ok(())
}
宏提取
使用 FromCssSelector
& selector
将 html 元素提取到结构中
// define struct and derive the FromCssSelector trait
#[derive(Debug, FromCssSelector)]
#[selector(path = "#user-repositories-list > ul > li")]
struct Repo {
#[selector(path = "a[itemprop~='name']", default = "<unname>", text)]
name: String,
#[selector(path = "span[itemprop~='programmingLanguage']", text)]
program_lang: Option<String>,
#[selector(path = "div.topics-row-container>a", text)]
topics: Vec<String>,
}
// request
let html = reqwest::get("https://github.com/holmofy?tab=repositories")
.await?
.css_selector()
.await?;
// Use the generated `from_html` method to extract data into the struct
let items = Repo::from_html(html)?;
items.iter().for_each(|item| println!("{:?}", item));
使用 FromXPath
& xpath
将 html 元素提取到结构中
// define struct and derive the FromXPath trait
#[derive(Debug, FromXPath)]
#[xpath(path = "//div[@id='user-repositories-list']/ul/li")]
struct Repo {
#[xpath(path = ".//a[contains(@itemprop,'name')]/text()", default = "<unname>")]
name: String,
#[xpath(path = ".//span[contains(@itemprop,'programmingLanguage')]/text()")]
program_lang: Option<String>,
#[xpath(path = ".//div[contains(@class,'topics-row-container')]/a/text()")]
topics: Vec<String>,
}
let html = reqwest::get("https://github.com/holmofy?tab=repositories")
.await?
.xpath()
.await?;
// Use the generated `from_xhtml` method to extract data into the struct
let items = Repo::from_xhtml(html)?;
items.iter().for_each(|item| println!("{:?}", item));
相关项目
依赖关系
~4–19MB
~233K SLoC