RUST实战代码:提取网页中的链接

2023-06-0408:51:30编程语言入门到精通Comments883 views字数 726阅读模式

获取某个网页中的链接, 只需要得到网页中所有a标签的href属性文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/44286.html

依赖(Cargo.toml)

[package]
name = "links-extrack"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
error-chain = "0.12.4"
reqwest = "0.11.12"
select = "0.5.0"
tokio = { version = "1.21.2", features = ["full"] }

代码

use error_chain::error_chain;
use select::document::Document;
use select::predicate::Name;
// 错误处理
error_chain! {
    foreign_links{
        Reqerror(reqwest::Error);
        IoError(std::io::Error);
    }
}
#[tokio::main]
async fn main()->Result<()> {
    let res= reqwest::get("http://www.rust-lang.org/zh-CN/")
        .await?
        .text() // 获取文本
        .await?;
    Document::from(res.as_str())
        // 找到a标签
        .find(Name("a"))
        // 过滤得到带href属性的
        .filter_map(|n| n.attr("href"))
        .for_each(|x| println!("{}", x));
    Ok(())
}

运行

RUST实战代码:提取网页中的链接
文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/44286.html
  • 本站内容整理自互联网,仅提供信息存储空间服务,以方便学习之用。如对文章、图片、字体等版权有疑问,请在下方留言,管理员看到后,将第一时间进行处理。
  • 转载请务必保留本文链接:https://www.cainiaoxueyuan.com/ymba/44286.html

Comment

匿名网友 填写信息

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定