需求
使用Selenium写一个脚本页面
代码
正常写页面都使用 name id xpath 这些元素定位
1.xpath获取方式
2.使用方法 详情百度Selenium使用就有更多方法了
//输入
driver.findElement(new By.ByXPath(“xpath”)).sendKeys(“你好”);
//点击
driver.findElement(new By.ByXPath(“xpath”)).click();
3.发现的问题
但是我发现页面加载需要时间,页面没加载完成方法就走完了,点击事件找不到就报错了
问题解决方法
//点击,输入事件方法前加一个睡眠等待页面加载完即可
Thread.sleep(1000);
4.问题优化
虽然使用了强制等待但是每个页面每个接口等待时间都不一样,而且这样等待的时间太长,这时候我去找了找方法发,发现一个隐式等待和显式等待
问题优化解决
创建一个SeleniumUtil 类 我用的是显示等待,WebDriverWait(驱动,等待时间)
这样5秒内找到了就返回true未找到就返回false,这个方法在5秒内每0.5秒去找一次,直到发现为止
//点击事件
public static boolean click(WebDriver driver, String Xpath) {
try {
new WebDriverWait(driver, 5).until(ExpectedConditions.presenceOfElementLocated(new By.ByXPath(Xpath))).click();
}catch (Exception e){
return false;
}
return true;
}
//输入事件
public static boolean sendKeys(WebDriver driver, String Xpath, String value){
try {
new WebDriverWait(driver, 5).until(ExpectedConditions.presenceOfElementLocated(new By.ByXPath(Xpath))).sendKeys(value);
}catch (Exception e){
return false;
}
return true;
}
完整代码
package com.selenium.demo;
import com.selenium.demo.Util.SeleniumUtil;
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
public class SeleniumDemo {
//访问地址
private static final String url = "http://localhost/auto";
public static void main(String[] args) throws InterruptedException {
//设置驱动,后面的路径自己要选择正确,也可以放在本地
System.setProperty("webdriver.chrome.driver", "D:\\WORK\\selenium\\chromedriver.exe");
//创建参数配置
ChromeOptions options = new ChromeOptions();
//配置远程地址
options.setExperimentalOption("debuggerAddress", "127.0.0.1:9222");
//加载驱动
WebDriver driver = new ChromeDriver(options);
//打开页面
driver.get(url);
//点击新增
SeleniumUtil.click(driver,"//*[@id=\"app\"]/div/div[2]/section/div/div[1]/div[1]/button");
//输入名称
SeleniumUtil.sendKeys(driver,"/html/body/div[2]/div/div[2]/form/div[1]/div/div/input","李四");
//点击性别下拉
SeleniumUtil.click(driver,"/html/body/div[2]/div/div[2]/form/div[2]/div/div/div[1]/input");
//选择男
SeleniumUtil.click(driver,"/html/body/div[4]/div[1]/div[1]/ul/li[1]");
//输入年龄
SeleniumUtil.sendKeys(driver,"/html/body/div[2]/div/div[2]/form/div[3]/div/div/input","18");
//点击确定
SeleniumUtil.click(driver,"/html/body/div[2]/div/div[3]/div/button[1]");
//表单输入李四名称
SeleniumUtil.sendKeys(driver,"//*[@id=\"app\"]/div/div[2]/section/div/form/div[1]/div/div/input","李四");
//点击搜索
SeleniumUtil.click(driver,"//*[@id=\"app\"]/div/div[2]/section/div/form/div[4]/div/button[1]");
//点击删除
SeleniumUtil.click(driver,"//*[@id=\"app\"]/div/div[2]/section/div/div[2]/div[3]/table/tbody/tr/td[5]/div/button[2]");
//确定删除
SeleniumUtil.click(driver,"/html/body/div[4]/div/div[3]/button[2]");
}
}