三.第一个selenium程序
public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "C:\\Users\\weidiao\\Desktop\\chromedriver_win32\\chromedriver.exe"); WebDriver webDriver = new ChromeDriver(); webDriver.manage().window().maximize(); webDriver.get("http://www.baidu.com"); WebElement kw = webDriver.findElement(By.id("kw")); kw.sendKeys("暗算"); WebElement su = webDriver.findElement(By.id("su")); su.click(); //webDriver.close(); System.out.println("Hello World!"); } |
运行这个程序,就会打开百度,输入"暗算",点击搜索按钮.
四.API简介
要看selenium api,不要看博客,直接去官网上的documents页面查看api.
1.等待某个条件完成
有时需要等待浏览器运行js结束之后,再分析html页面.new出来一个WebDriverWait对象,调用它的until(ExpectedCondition<>condition)函数.
// Google's search is rendered dynamically with JavaScript. // Wait for the page to load, timeout after 10 seconds (new WebDriverWait(driver, 10)).until(new ExpectedCondition<Boolean>() { public Boolean apply(WebDriver d) { return d.getTitle().toLowerCase().startsWith("cheese!"); } }); |
2.获取元素
//通过id WebElement element = driver.findElement(By.id("coolestWidgetEvah")); //通过className List<WebElement> cheeses = driver.findElements(By.className("cheese")); //通过tagName WebElement frame = driver.findElement(By.tagName("iframe")); //通过name WebElement cheese = driver.findElement(By.name("cheese")); //通过linkText <a href="http://www.google.com/search?q=cheese">cheese</a> WebElement cheese = driver.findElement(By.linkText("cheese")); //通过部分linkText <a href="http://www.google.com/search?q=cheese">search for cheese</a> WebElement cheese = driver.findElement(By.partialLinkText("cheese")); //通过css <div id="food"><span class="dairy">milk</span><span class="dairy aged">cheese</span></div> WebElement cheese = driver.findElement(By.cssSelector("#food span.dairy.aged")); //通过xpath,比较麻烦 //通过javaScript WebElement element = (WebElement) ((JavascriptExecutor)driver).executeScript("return $('.cheese')[0]"); List<WebElement> labels = driver.findElements(By.tagName("label")); List<WebElement> inputs = (List<WebElement>) ((JavascriptExecutor)driver).executeScript( "var labels = arguments[0], inputs = []; for (var i=0; i < labels.length; i++){" + "inputs.push(document.getElementById(labels[i].getAttribute('for'))); } return inputs;", labels); |
3.操作元素
一个WebElement可以对应html很多控件,如按钮,单选按钮(select和deselect,click),复选按钮(跟单选按钮差不多),表单(submit),文件上传可以进行上传文件(sendKeys)
除了WebElement还有Select,表示多选的下拉列表.
上文内容不用于商业目的,如涉及知识产权问题,请权利人联系博为峰小编(021-64471599-8017),我们将立即处理。