Java selenium 基本使用

此功能是抓取本地文件里面的数据,然后填充到web应用上的指定输入框

1.首先下载 msedgedriver

2 其次获取Xpath

3.配置selenium 仓库地址

java 复制代码
package com.example.automation;

import org.openqa.selenium.*;
import org.openqa.selenium.edge.EdgeDriver;

import java.io.*;

public class WorkOrderAutomation {
    public static void main(String[] args) throws InterruptedException, IOException {

        System.setProperty("webdriver.edge.driver", "C:\\Windows\\System32\\msedgedriver.exe");

        WebDriver driver = new EdgeDriver();

        driver.get("http://localhost:3000/workorder/workorder");
        Thread.sleep(20000);
        String myXPath ="//input[@placeholder='请输入工单名称']";
        BufferedReader reader = new BufferedReader(new FileReader("C:\\Users\\zhihu.wang\\Desktop\\LotSN.txt"));
        String data;
        while((data = reader.readLine()) != null){

            try {
                //查找元素
                WebElement element = driver.findElement(By.xpath(myXPath));
                element.clear();
                //输入值
                element.sendKeys(reader.readLine());
                //回车
                element.sendKeys(Keys.RETURN);
                //延迟2秒
                Thread.sleep(2000);

            } catch (Exception e) {
                System.out.println("错误:" + e.getMessage());
            }
        }
        //等待五秒关闭浏览器
        Thread.sleep(5000);
        driver.quit();
    }
}

4.有时候复制的Xpath不准,需要在浏览器控制台运行下面代码获取Xpath。

// 查找所有非隐藏输入框

var inputs = Array.from(document.querySelectorAll('input:not(type="hidden")'));

inputs.forEach((input, index) => {

console.log(`${index+1}`, {

placeholder: input.placeholder,

id: input.id,

name: input.name,

class: input.className,

type: input.type

});

});

相关推荐
一叶飘零_sweeeet18 分钟前
IDEA 插件 Trae AI 最新全攻略(基于 TRAE AI: Coding Assistant 1.7.0.0)
java·intellij-idea·trae
KobeSacre25 分钟前
CyclicBarrier 源码
java·jvm·算法
我登哥MVP43 分钟前
Hadoop成长史-从Nutch子项目到大数据生态王者
java·大数据·hadoop·分布式·云原生·云计算
进击切图仔1 小时前
SAM3 微调标注流水线和 Label Studio
java·服务器·前端
名字还没想好☜1 小时前
Go error 处理:errors.Is/As 与错误包装
开发语言·后端·golang·go·错误处理
红糖奶茶1 小时前
Python 中 while 循环计数异常的常见原因分析与正确搓搓
开发语言·python
java1234_小锋1 小时前
Maven 4 要来了:15 年后,Java 构建工具迎来“彻底重构“
java·重构·maven
Lucky_Turtle1 小时前
【论文写作】PDF图片不清晰,打印生成PDF空白大,PDF字体嵌入
开发语言·pdf·c#
csdndenglu1 小时前
Easy3D:一个轻量级、易用、高效的C++库,用于处理和渲染3D数据,无复杂要求时可替代VTK
开发语言·c++·图形渲染·3d渲染
霸道流氓气质1 小时前
Java 工程师 AI 智能体学习路线 · 阶段 1:AI / LLM 基础认知 详解
java·人工智能·学习