rust - 如何将网站的内容下载到字符串中?
问题描述
我只想下载一个网站并将其内容放入String
.
类似于在 C# 中的操作方式:
WebClient c = new WebClient();
string ex = c.DownloadString("http://url.com");
解决方案
Rust在标准库中没有 HTTP 功能,因此您可能希望使用另一个 crate(库)为您处理 HTTP 内容。为此目的,有几个不同的板条箱。
reqwest
: "更高级别的 HTTP 客户端库"
let body = reqwest::get("http://url.com")?.text()?;
ureq
: "最小的 HTTP 请求库"
let body = ureq::get("http://url.com").call().into_string()?
isahc
:“实用的 HTTP 客户端,使用起来很有趣。”
let mut response = isahc::get("https://example.org")?;
let body = response.text()?;
curl
: "Rust 绑定到 libcurl 以发出 HTTP 请求"
use curl::easy::Easy;
// First write everything into a `Vec<u8>`
let mut data = Vec::new();
let mut handle = Easy::new();
handle.url("http://url.com").unwrap();
{
let mut transfer = handle.transfer();
transfer.write_function(|new_data| {
data.extend_from_slice(new_data);
Ok(new_data.len())
}).unwrap();
transfer.perform().unwrap();
}
// Convert it to `String`
let body = String::from_utf8(data).expect("body is not valid UTF8!");
hyper
?
Hyper 是一个非常流行的 HTTP 库,但它的级别相当低。这使得它通常太难/太冗长而无法用于小脚本。但是,如果你想编写一个 HTTP 服务器,Hyper 肯定是要走的路(这就是大多数 Rust Web 框架使用 Hyper 的原因)。
好多其它的!
我无法在此答案中列出所有可用的库。因此,请随时搜索 crates.io 以获取更多可以帮助您的 crates。
推荐阅读
- python-3.x - Python 3 MQTT 客户端在 Sqlite 中存储接收到的有效负载 - 打开数据库一次,存储多次,最后关闭数据库?
- python - 即使在使用 PySpark 读取 .ORC 文件时明确指定,也缺少标题
- json - 从包含 JSON 的 API 链接导入数据到 EXCEL
- python - 拆分 2 个单词单元格并使用 python 插入新行
- html - 鼠标悬停时背景图像不会改变
- php - PHP:如何根据来自 SQL 组的记录通过查询在 TCPDF 中进行页面分组/分页
- python-3.x - Python Twisted 连续重新连接尝试
- python - Matplotlib:将线收集到同一轴上
- angular - Angular Material可扩展数据表不显示数据
- r - 如何从数据框中提取最后一个值并删除数字?