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

});

});

相关推荐
唐青枫1 天前
Java JDBC 实战指南:从 Connection 到事务和连接池
java
一个做软件开发的牛马1 天前
MyBatis-Plus 从零实战:完整搭建可运行 Demo,BaseMapper 零 SQL、Wrapper 条件构造、分页插件与代码生成器详解
java·后端
用户3721574261351 天前
Java 处理 PDF 图片:提取 PDF 中的图片,并压缩 PDF 图片体积
java
用户3721574261351 天前
Java 打印 Word 文档:从基础打印到高级设置
java
用户3521802454752 天前
当 Prompt 学会"热更新":Spring Boot × Nacos3 AI 实战
java·spring boot·ai编程
东坡白菜2 天前
破局全栈:一个前端开发的Java入门实战记录(1)
java·全栈
唐青枫2 天前
Java Tomcat 实战指南:从 Servlet 容器到 Spring Boot 部署
java
wsaaaqqq2 天前
roudan:自由选择实体、灵活操作数据、快速写入数据库的 Java 框架
java
plainGeekDev2 天前
null 判断 → Kotlin 可空类型
android·java·kotlin
糖拌西瓜皮2 天前
Java开发者视角:深入理解Node.js异步编程模型
java·后端·node.js