我试图遵循这里的示例:https://rust-lang-nursery.github.io/rust-cookbook/web/scraping.html,它利用Reqwest和Select来获得html响应,然后解析数据。
我使用ReqwestVersion0.10.4和SelectVersion0.4.3,这是它在示例中显示的版本。但是,我收到了一个错误:
error[E0277]: the trait bound `reqwest::Response: std::io::Read` is not satisfied
--> src/main.rs:19:25
|
19 | Document::from_read(res)?
| ^^^ the trait `std::io::Read` is not implemented for `reqwest::Response`
|
::: /root/.cargo/registry/src/github.com-1ecc6299db9ec823/select-0.4.3/src/document.rs:31:25
|
31 | pub fn from_read<R: io::Read>(mut readable: R) -> io::Result<Document> {
| -------- required by this bound in `select::document::Document::from_read`from_read方法似乎接受一个读类型,但是reqwest::get方法返回一个不同的类型。在将响应传递给from_read方法之前,是否必须先进行某种类型的转换?
这是一个例子:
#[macro_use]
extern crate error_chain;
extern crate reqwest;
extern crate select;
use select::document::Document;
use select::predicate::Name;
error_chain! {
foreign_links {
ReqError(reqwest::Error);
IoError(std::io::Error);
}
}
fn main() -> Result<()> {
let res = reqwest::get("https://www.rust-lang.org/en-US/").await?;
Document::from_read(res)?
.find(Name("a"))
.filter_map(|n| n.attr("href"))
.for_each(|x| println!("{}", x));
Ok(())
}发布于 2020-05-25 08:56:14
reqwest::get返回一个Result<Response>,然后使用?展开Result,这意味着您现在有一个Response对象作为文档化的这里。而且,由于web调用可以成功地发生,但仍然失败(请参阅HTTP 200代码),您应该检查响应代码,但是由于这是为了学习,我们将忽略它。您想要的是一个实现std::io::Read特性的结构,阅读它可以看出String实现了这个特性。回到reqwest::Response,我们可以使用text()方法获得返回的字符串。所以你的代码现在变成
let res = reqwest::get("https://www.rust-lang.org/en-US/")
.await?
.text()
.await?;注释更新:现在的问题是,Document::from_read只接受std::io::Read作为参数,而std::string::String没有实现该特性,我们可以使用Document::from作为文档实现From<&'a str>特性,而不是使用stringreader这样的板条箱。
而且,和几乎所有的东西一样,有多种方法可以解决这个问题。你可以
Document::from(res)从字符串创建文档,或Document::from_read(res.as_bytes())创建文档。https://stackoverflow.com/questions/61996298
复制相似问题