昨天做个小任务,其中有一步需要执行重复操作,就是select下拉框中勾选option项然后提交。然后再勾选再提交。
提交了几次,太重复太有规律了,花半小时写个代码代替这种重复操作是不是更好。
想好了,就开写,虽然还有点小问题,但基本可以代替部分重复工作了。
package MonitorTest;import java.io.BufferedReader;import java.io.File;import java.io.FileInputStream;import java.io.IOException;import java.io.InputStreamReader;import java.util.ArrayList;import org.openqa.selenium.By;import org.openqa.selenium.WebDriver;import org.openqa.selenium.WebElement;import org.openqa.selenium.firefox.FirefoxDriver;import org.openqa.selenium.support.ui.ExpectedCondition;import org.openqa.selenium.support.ui.Select;import org.openqa.selenium.support.ui.WebDriverWait;public class MonitorTest { public static void main(String[] args) throws InterruptedException, IOException{ //存储监控 名称的文件地址 String fileUrl="D:\\bukejian\\tmp.txt"; //访问地址 String url=; ArrayListlist = new ArrayList (); String encoding="GBK"; File file = new File(fileUrl); if(file.isFile() && file.exists()){ InputStreamReader read = new InputStreamReader( new FileInputStream(file),encoding); BufferedReader bufferedReader = new BufferedReader(read); String lineTxt = null; while((lineTxt = bufferedReader.readLine()) != null){ list.add(lineTxt); } read.close(); }else{ System.out.println("No exist"); } System.setProperty("webdriver.firefox.bin", "D:/bukejian/Mozilla Firefox/firefox.exe"); WebDriver dr = new FirefoxDriver(); dr.get(url); WebElement submit=(new WebDriverWait(dr,10)).until(new ExpectedCondition (){ @Override public WebElement apply(WebDriver d){ return d.findElement(By.cssSelector("input[type=\"submit\"]")); } }); dr.findElement(By.name("login_username")).clear(); Thread.sleep(1000); dr.findElement(By.name("login_username")).sendKeys("bukejian"); Thread.sleep(1000); dr.findElement(By.name("login_password")).clear(); dr.findElement(By.name("login_password")).sendKeys("bukejian"); submit.click(); Thread.sleep(5000); for(String a :list){ WebElement add=(new WebDriverWait(dr,10)).until(new ExpectedCondition (){ @Override public WebElement apply(WebDriver d){ return d.findElement(By.linkText("Add")); } }); add.click(); WebElement select=(new WebDriverWait(dr,10)).until(new ExpectedCondition (){ @Override public WebElement apply(WebDriver d){ return d.findElement(By.name("type_select")); } }); new Select(dr.findElement(By.name("type_select"))).selectByVisibleText("Graph"); new Select(dr.findElement(By.id("local_graph_id"))).selectByVisibleText(a); dr.findElement(By.cssSelector("input[type=\"submit\"]")).click();//提交 } dr.close(); }}
代码还是有些问题,好像出自等待时间上面,一直不太懂selenium的等待时间的用法,好好看一下