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

});

});

相关推荐
后端AI实验室4 小时前
用AI写代码,我差点把漏洞发上线:血泪总结的10个教训
java·ai
程序员清风6 小时前
小红书二面:Spring Boot的单例模式是如何实现的?
java·后端·面试
belhomme6 小时前
(面试题)Redis实现 IP 维度滑动窗口限流实践
java·面试
Be_Better6 小时前
学会与虚拟机对话---ASM
java
开源之眼8 小时前
《github star 加星 Taimili.com 艾米莉 》为什么Java里面,Service 层不直接返回 Result 对象?
java·后端·github
Maori3169 小时前
放弃 SDKMAN!在 Garuda Linux + Fish 环境下的优雅 Java 管理指南
java
用户9083246027310 小时前
Spring AI 1.1.2 + Neo4j:用知识图谱增强 RAG 检索(上篇:图谱构建)
java·spring boot
小王和八蛋10 小时前
DecimalFormat 与 BigDecimal
java·后端
beata10 小时前
Java基础-16:Java内置锁的四种状态及其转换机制详解-从无锁到重量级锁的进化与优化指南
java·后端
IT探险家10 小时前
你的第一个 Java 程序就翻车?HelloWorld 的 8 个隐藏陷阱
java