在 Rust 中进行网页数据采集通常需要使用 HTTP 客户端库和 HTML 解析库。一个流行的 HTTP 客户端库是 reqwest,用于发出 HTTP 请求;而对于 HTML 解析,可以使用库如 scraper。
首先,您需要在 Cargo.toml 中添加依赖:
[dependencies]
reqwest = { version = "0.11", features = ["blocking", "json"] }
http://www.jshk.com.cn/mb/reg.asp?kefu=xiaoding;//爬虫IP免费获取;
scraper = "0.12"
接下来是一个基本的示例,展示如何使用 Rust 中的 reqwest 和 scraper 库来采集马蜂窝的数据。
use reqwest::blocking::Client;
use scraper::{Html, Selector};
fn fetch_mafengwo_data() -> Result<(), Box<dyn std::error::Error>> {
// 创建一个 HTTP 客户端
let client = Client::new();
// 发送 GET 请求到马蜂窝网站
let res = client.get("https://www.mafengwo.cn/").send()?;
// 检查请求是否成功
if res.status().is_success() {
// 使用 scraper 解析 HTML 内容
let body = res.text()?;
let document = Html::parse_document(&body);
// 使用选择器来定位需要的元素
let title_selector = Selector::parse("h2.title").unwrap(); // 假设标题在h2标签中
let description_selector = Selector::parse("p.description").unwrap(); // 假设描述在p标签中
// 获取所有符合选择器条件的元素
let titles = document.select(&title_selector);
let descriptions = document.select(&description_selector);
// 遍历并输出数据
for (title, description) in titles.zip(descriptions) {
println!("标题: {}", title.text().collect::<String>());
println!("描述: {}", description.text().collect::<String>());
println!("=".repeat(50));
}
} else {
println!("Failed to fetch data: {}", res.status());
}
Ok(())
}
fn main() {
if let Err(err) = fetch_mafengwo_data() {
eprintln!("Error: {}", err);
}
}
这个示例使用了 reqwest 发送 HTTP GET 请求到马蜂窝网站,并使用 scraper 库解析 HTML 内容。在示例中,使用了假设的选择器来查找标题和描述信息。实际情况中,您需要根据马蜂窝网站的页面结构调整选择器和数据提取的方式。
标签:HTTP,description,title,马蜂窝,scraper,采集,reqwest,let,Rust From: https://blog.51cto.com/u_16479648/9078261