我正在尝试按照这个例子:https://rust-lang-nursery.github.io/rust-cookbook/web/scraping.html,使用Reqwest和Select获取HTML响应并解析数据。
我使用的是Reqwest 0.10.4版本和Select 0.4.3版本,这也是该示例中展示的版本。但是,我遇到了一个错误:
我使用的是Reqwest 0.10.4版本和Select 0.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 方法需要一个 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(())
}
&'a [u8]
,所以你可以在String上调用as_bytes
。 - MindSwipeDocument::from(res)
而不是Document::from_read()
,因为Document结构实现了From<&'a str>
特质,如此文档所述这里。 - MindSwipeimpl<'a> From<&'a str> for Document
。也许你需要显式地转换它,比如Document::from(&res[..])
(这将返回 res 的完整切片)或者像Document::from(&*res)
那样解引用字符串。是的,创建一个文件并读取它是次优的。 - MindSwipe