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
相关推荐
yezipi耶不耶6 小时前
用 Rust 带你了解 TCP 和 UDP
tcp/ip·rust·udp
勇敢牛牛_13 小时前
使用Rust开发的智能助手系统,支持多模型、知识库和MCP
ai·rust·rag·mcp
Source.Liu19 小时前
【typenum】 8 常量文件(consts.rs)
rust
Liigo1 天前
LIIGO ❤️ RUST 12 YEARS
rust·纪念日·编程语言·liigo·十周年
明月看潮生2 天前
青少年编程与数学 02-019 Rust 编程基础 16课题、包、单元包及模块
开发语言·青少年编程·rust·编程与数学
后青春期的诗go2 天前
基于Rust语言的Rocket框架和Sqlx库开发WebAPI项目记录(二)
开发语言·后端·rust·rocket框架
yezipi耶不耶2 天前
Rust入门之高级Trait
开发语言·后端·rust
后青春期的诗go2 天前
基于Rust语言的Rocket框架和Sqlx库开发WebAPI项目记录(一)
开发语言·后端·rust
景天科技苑2 天前
【Rust闭包】rust语言闭包函数原理用法汇总与应用实战
开发语言·后端·rust·闭包·闭包函数·rust闭包·rust闭包用法
欧先生^_^2 天前
rust语言,与c,go语言一样也是编译成二进制文件吗?
c语言·golang·rust