Rust Web自动化Demo

1.新建项目

使用RustCover新建项目,目录如下:

Cargo.toml文件

rust 复制代码
[package]
name = "Demo"
version = "0.1.0"
edition = "2021"

[dependencies]
tokio = { version = "1", features = ["full"] }
thirtyfour = { version = "0.31.0", features = ["component"] }
scraper = "0.15.0"

2.编写代码

以百度网站为例

rust 复制代码
use std::time::Duration;
use thirtyfour::By;
use tokio;
use thirtyfour::prelude::{DesiredCapabilities, WebDriver, WebDriverResult};

#[tokio::test]
async fn navigate_to_url() -> WebDriverResult<()> {
    let capabilities = DesiredCapabilities::chrome();
    let driver = WebDriver::new("http://localhost:9515", capabilities)
        .await
        .expect("Failed to connect to localhost:9515!");
    driver.maximize_window().await?;
    driver.set_implicit_wait_timeout(std::time::Duration::from_secs(10)).await?;
    tokio::time::sleep(Duration::from_secs(3)).await;
    driver
        .goto("https://www.baidu.com")
        .await
        .expect("Couldn't navigate to the URL!");
    tokio::time::sleep(Duration::from_secs(2)).await;
    let search_input = driver.find(By::Id("kw")).await?;
    search_input.send_keys("Hello").await?;
    tokio::time::sleep(Duration::from_secs(2)).await;
    let search_button = driver.find(By::Id("su")).await?;
    search_button.click().await?;
    tokio::time::sleep(Duration::from_secs(2)).await;
    let page_title = driver.title()
        .await
        .expect("Page title not found");
    driver.quit().await?;
    assert_eq!(
        page_title,
        "Hello_百度搜索"
    );
    Ok(())
}

3.运行项目

在RustCover打开终端,输入命令:

bash 复制代码
chromedriver --port=9515

然后再新建终端,输入命令:

bash 复制代码
cargo test
相关推荐
对象存储与RustFS5 小时前
自建对象存储的第一个决定:单机就够,还是必须上分布式
后端·rust·开源
geovindu9 小时前
rust: tree
开发语言·后端·rust
孙启超10 小时前
【AI开发之Rust】第 21 课:双端集成与出包 —— Android(.so→AAR)与 iOS(xcframework)
开发语言·后端·rust
鬓戈20 小时前
Rust 语言与 AI 应用生态调研及学习路径
人工智能·学习·rust
孙启超1 天前
【AI开发之Rust】第 19 课:UniFFI 导出核心能力
开发语言·后端·rust
孙启超1 天前
【AI开发之Rust】第 17 课:项目总览与核心架构 —— AI 助手 Rust 核心从 0 到 1
开发语言·后端·rust
柯南46681 天前
【AI开发之Rust】第 21 课:双端集成与出包 —— Android(.so→AAR)与 iOS(xcframework)
rust·编程语言
Amos_Web1 天前
Rspack 源码解析(十六):多类型资源如何进入 Compilation.assets
前端·rust·前端框架
Norna1 天前
时间轮里那行凭空出现的 +1
rust
隔窗听雨眠1 天前
FunProxy用Rust构建跨平台全链路测试抓包代理工具
开发语言·后端·rust