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
相关推荐
leoZ23117 小时前
Vue3 还原一个企业级后台-14-项目总结
开发语言·人工智能·后端·opencv·计算机视觉·数据挖掘·rust
特立独行的猫a19 小时前
Tauri v2的Rust应用 → HarmonyOS(鸿蒙 PC)移植30分钟速成指南
开发语言·rust·harmonyos·tauri·移植·鸿蒙pc
程序员爱钓鱼19 小时前
Rust 方法 Method详解:self、方法调用与API设计
后端·面试·rust
Patrick_Wilson1 天前
sccache 用在 Rust 上为什么常「不省编译」:原理、限制与 Windows 接入
ci/cd·rust·编译器
k4m7v2pz2 天前
rvs 26.8.43 → 26.8.53 更新概览:MCP 落地、审计增强与谬误澄清
rust·repl·mcp server·rust-verb-shell·rvs·shell 工具
程序员爱钓鱼2 天前
Rust impl详解:为Struct定义方法与关联函数
前端·后端·rust
k4m7v2pz2 天前
Rust 程序在 ReactOS 上“加载即崩“:从崩溃地址 0x6107104d 到 CRT 依赖的深度排查
rust·交叉编译·逆向工程·reactos·pe格式·windows兼容
Thneonl2 天前
一个人从 Rust 内核做到 React 前端:我做了一个云原生 SRE 巡检图谱桌面工具
rust
程序员爱钓鱼2 天前
Rust Struct结构体详解:定义自己的复杂数据类型
后端·面试·rust
苏灿烤鱼2 天前
公司**不可计算,就自己做操作系统
rust·typescript·agent