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
相关推荐
前端与小赵17 小时前
什么是Sass,有什么特点
前端·rust·sass
一个小坑货18 小时前
Rust基础
开发语言·后端·rust
Object~19 小时前
【第九课】Rust中泛型和特质
开发语言·后端·rust
码农飞飞1 天前
详解Rust结构体struct用法
开发语言·数据结构·后端·rust·成员函数·方法·结构体
Dontla2 天前
Rust derive macro(Rust #[derive])Rust派生宏
开发语言·后端·rust
fqbqrr2 天前
2411rust,编译时自动检查配置
rust
梦想画家2 天前
用Rust中byteorder包高效处理字节序列
rust·序列化·byteorder·文件编码
beifengtz2 天前
【Rust调用Windows API】读取系统CPU利用率
windows·rust·windows api
梦想画家2 天前
精通Rust系统教程-过程宏入门
rust·元编程·rust宏
fqbqrr2 天前
2411rust,1.81,1.82
rust