南通營銷型網(wǎng)站建設(shè)自媒體平臺注冊官網(wǎng)
一. Selenium介紹
selenium 是用來做web自動化測試的框架,支持各種瀏覽器,各種,支持各種語言?
原理:
二. 元素定位
2.1 XPath 定位
絕對路徑: /html/head/title
相對路徑以雙斜杠開頭,常見的相對路徑定位有以下幾種:
<1>相對路徑+索引: 索引是從1開始的
<2>相對路徑+屬性值:
<3>相對路徑+通配符
<4>相對路徑+文本匹配
2.2 CSS定位
? id選擇器: #id
? 類選擇器: .class
? 標(biāo)簽選擇: 標(biāo)簽名
? 后代選擇器: 父級選擇器 子級選擇器
三. 操作測試對象
3.1 常見API
? click 點擊對象
? send_keys 在對象上模擬按鍵輸入
? clear 清除對象輸入的文本內(nèi)容
? submit 提交
? getAttribute 獲取標(biāo)簽中value屬性所對應(yīng)的值
? text 由于獲取元素的文本信息
public class Demo1 {public static void main(String[] args) throws InterruptedException {ChromeOptions options=new ChromeOptions();//允許所有請求options.addArguments("--remote-allow-origins=*");WebDriver webDriver =new ChromeDriver(options);//獲取網(wǎng)址webDriver.get("https://www.sogou.com");//獲取value標(biāo)簽元素文本信息String str=webDriver.findElement(By.xpath("//input[@value=\"搜狗搜索\"]")).getAttribute("value");System.out.println(str);//輸入搜索內(nèi)容webDriver.findElement(By.cssSelector("#query")).sendKeys("軟件測試");Thread.sleep(3000);webDriver.findElement(By.xpath("//input[@value=\"搜狗搜索\"]")).click();Thread.sleep(3000);//找到并打印所有a標(biāo)簽下em標(biāo)簽中的內(nèi)容List<WebElement> elements=webDriver.findElements(By.cssSelector("a em"));for (int i = 0; i < elements.size(); i++) {System.out.println(elements.get(i).getText());}Thread.sleep(3000);webDriver.close();}
}
public static void main(String[] args) throws InterruptedException {ChromeOptions options=new ChromeOptions();options.addArguments("--remote-allow-origins=*");WebDriver webDriver=new ChromeDriver(options);webDriver.get("https://www.sogou.com/");Thread.sleep(3000);webDriver.findElement(By.cssSelector("#query")).sendKeys("軟件測試");Thread.sleep(3000);//由于此處的搜狗搜索在form標(biāo)簽中,因此能夠順利提交//webDriver.findElement(By.cssSelector("#stb")).click();webDriver.findElement(By.cssSelector("#stb")).submit();Thread.sleep(3000);//此時代碼是會報錯的,因為a標(biāo)簽并不在form標(biāo)簽內(nèi)//webDriver.findElement(By.cssSelector("#weixinch")).submit();webDriver.close();}
3.2 等待
public static void main(String[] args) throws InterruptedException {ChromeOptions options=new ChromeOptions();options.addArguments("--remote-allow-origins=*");WebDriver webDriver=new ChromeDriver(options);webDriver.get("https://www.baidu.com/");webDriver.findElement(By.cssSelector("#s-top-loginbtn")).click();//隱式等待//webDriver.manage().timeouts().implicitlyWait(3, TimeUnit.DAYS);//顯示等待,若加載出直接執(zhí)行下面代碼,若在指定時間內(nèi)沒有加載出來,就拋異常new WebDriverWait(webDriver,10).until(ExpectedConditions.presenceOfElementLocated(By.cssSelector("#s-top-loginbtn")));//強制等待3sThread.sleep(3000);webDriver.findElement(By.xpath("//*[@id=\"TANGRAM__PSP_11__userName\"]")).sendKeys("1111");webDriver.close();}
隱式等待等待的是整個頁面的元素,而顯示等待等待的是一定的條件.?
3.3 打印信息(標(biāo)題/URL)
public static void main(String[] args) {ChromeOptions options =new ChromeOptions();options.addArguments("--remote-allow-origins=*");WebDriver webDriver=new ChromeDriver(options);webDriver.get("https://www.sogou.com/");String title=webDriver.getTitle();String url=webDriver.getCurrentUrl();System.out.println("當(dāng)前標(biāo)題:"+title+"當(dāng)前url:"+url);webDriver.close();}
3.4 瀏覽器的操作
public static void main(String[] args) throws InterruptedException {ChromeOptions options=new ChromeOptions();options.addArguments("--remote-allow-origins=*");WebDriver webDriver=new ChromeDriver(options);webDriver.get("https://www.sogou.com");webDriver.findElement(By.cssSelector("#query")).sendKeys("軟件測試");webDriver.findElement(By.cssSelector("#stb")).click();webDriver.manage().timeouts().implicitlyWait(3, TimeUnit.DAYS);//后退一步webDriver.navigate().back();Thread.sleep(3000);//前進一步webDriver.navigate().forward();Thread.sleep(3000);//使屏幕最大化webDriver.manage().window().maximize();Thread.sleep(3000);//全屏webDriver.manage().window().fullscreen();Thread.sleep(3000);//自定義窗口大小webDriver.manage().window().setSize(new Dimension(600,1000));Thread.sleep(3000);//滑動滾動條((JavascriptExecutor)webDriver).executeScript("document.documentElement.scrollTop=19999");}
3.5 鍵盤事件
通過sendKeys()調(diào)用按鍵:
? sendkeys(Keys.TAB) #TAB
??sendKeys(Keys.ENTER) #回車
??sendKeys(Keys.SPACE) #空格鍵
??sendKeys(Keys.ESCAPE) #回退鍵(Esc)
public static void main(String[] args) throws InterruptedException {ChromeOptions options=new ChromeOptions();options.addArguments("--remote-allow-origins=*");WebDriver webDriver=new ChromeDriver(options);webDriver.get("https://www.sogou.com/");Thread.sleep(3000);webDriver.findElement(By.cssSelector("#query")).sendKeys("軟件測試");Thread.sleep(3000);webDriver.findElement(By.cssSelector("#query")).sendKeys(Keys.SPACE);Thread.sleep(3000);webDriver.findElement(By.cssSelector("#query")).sendKeys("軟件開發(fā)");Thread.sleep(3000);webDriver.findElement(By.cssSelector("#query")).sendKeys(Keys.ENTER);}
鍵盤組合鍵用法?
sendKeys(Keys.CONTROL,"a") #全選 (Ctrl+a)
sendKeys(Keys.CONTROL,"c")?#復(fù)制?(Ctrl+c)
sendKeys(Keys.CONTROL,"x")?#剪切?(Ctrl+x)
sendKeys(Keys.CONTROL,"v")?#粘貼?(Ctrl+v)
public static void main(String[] args) throws InterruptedException {ChromeOptions options=new ChromeOptions();options.addArguments("--remote-allow-origins=*");WebDriver webDriver=new ChromeDriver(options);webDriver.get("https://www.sogou.com/");webDriver.findElement(By.cssSelector("#query")).sendKeys("軟件測試");Thread.sleep(3000);webDriver.findElement(By.cssSelector("#query")).sendKeys(Keys.CONTROL,"a");Thread.sleep(3000);webDriver.findElement(By.cssSelector("#query")).sendKeys(Keys.CONTROL,"x");Thread.sleep(3000);webDriver.findElement(By.cssSelector("#query")).sendKeys(Keys.CONTROL,"v");Thread.sleep(3000);webDriver.findElement(By.cssSelector("#query")).sendKeys(Keys.ENTER);}
3.6 鼠標(biāo)事件
Actions類:
? contextClick() 右擊
? doubleClick() 雙擊
? dragAndDrop() 拖動
? moveToElement() 移動
public static void main(String[] args) throws InterruptedException {ChromeOptions options=new ChromeOptions();options.addArguments("--remote-allow-origins=*");WebDriver webDriver=new ChromeDriver(options);webDriver.get("https://www.sogou.com/");webDriver.findElement(By.cssSelector("#query")).sendKeys("軟件測試");webDriver.findElement(By.cssSelector("#query")).sendKeys(Keys.ENTER);Actions actions=new Actions(webDriver);Thread.sleep(3000);//需要現(xiàn)將鼠標(biāo)移動到要操作的元素,然后右擊,要perform()才會有效果actions.moveToElement( webDriver.findElement(By.cssSelector("#sogou_weixin"))).contextClick().perform();}
四. 特殊操作
為了方便測試的演示,測試的頁面都是自制的。
4.1 定位一組元素
頁面:
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title>
</head>
<body><h3>checkbox</h3>
<div class="well">
<form class="form-horizontal">
<div class="control-group">
<label class="control-label" for="c1">checkbox1</label>
<div class="controls">
<input type="checkbox" id="c1" />
</div>
</div>
<div class="control-group">
<label class="control-label" for="c2">checkbox2</label>
<div class="controls">
<input type="checkbox" id="c2" />
</div>
</div>
<div class="control-group">
<label class="control-label" for="c3">checkbox3</label>
<div class="controls">
<input type="checkbox" id="c3" />
</div>
</div>
<div class="control-group">
<label class="control-label" for="r">radio1</label>
<div class="controls">
<input type="radio" id="r1" />
</div>
</div>
<div class="control-group">
<label class="control-label" for="r">radio2</label>
<div class="controls">
<input type="radio" id="r2" />
</div>
</div>
</form>
</div>
</body>
</html>
測試:?
public static void main(String[] args) {ChromeOptions options=new ChromeOptions();options.addArguments("--remote-allow-origins=*");WebDriver webDriver=new ChromeDriver(options);webDriver.get("http://localhost:63342/SeleniumTest/page/test1.html?_ijt=a28mk13t2kbijoe7d2clon53lj&_ij_reload=RELOAD_ON_SAVE");webDriver.manage().timeouts().implicitlyWait(3,TimeUnit.DAYS);List<WebElement> webElements=webDriver.findElements(By.xpath("//input[@type=\"checkbox\"]"));for (int i = 0; i < webElements.size(); i++) {System.out.println(webElements.get(i).getAttribute("type"));}}
4.2 多層框架/窗口定位
多框架定位
如果有內(nèi)嵌網(wǎng)頁框架,需要先轉(zhuǎn)到框架才能操作框架內(nèi)元素。
public static void main(String[] args) throws InterruptedException {ChromeOptions options=new ChromeOptions();//允許所有請求options.addArguments("--remote-allow-origins=*");WebDriver webDriver =new ChromeDriver(options);webDriver.get("https://mail.163.com/");//需要先定位到框架,再對框架內(nèi)元素進行操作webDriver.switchTo().frame(webDriver.findElement(By.xpath("//iframe")));Thread.sleep(3000);webDriver.findElement(By.xpath("//input[@name=\"email\"]")).sendKeys("12345");}
窗口的切換
在瀏覽器中每個窗口都有一個句柄來標(biāo)識
public static void main(String[] args) throws InterruptedException {ChromeOptions options=new ChromeOptions();options.addArguments("--remote-allow-origins=*");WebDriver webDriver=new ChromeDriver(options);webDriver.get("Https://www.baidu.com");//獲取當(dāng)前句柄String handle= webDriver.getWindowHandle();System.out.println(handle);Thread.sleep(3000);webDriver.findElement(By.cssSelector("#s-top-left > a:nth-child(1)")).click();Set<String> hanles=webDriver.getWindowHandles();for (String h:hanles) {handle=h;}webDriver.switchTo().window(handle);Thread.sleep(3000);webDriver.findElement(By.cssSelector("#ww")).sendKeys("新聞聯(lián)播");Thread.sleep(3000);webDriver.findElement(By.cssSelector("#s_btn_wr")).click();}
4.3 下拉框操作
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>下拉框</title>
</head>
<body>
<select id="ShippingMethod"onchange="updateShipping(options[selectedIndex]);" name="ShippingMethod"><option value="12.51">UPS Next Day Air ==> $12.51</option><option value="11.61">UPS Next Day Air Saver ==> $11.61</option><option value="10.69">UPS 3 Day Select ==> $10.69</option><option value="9.03">UPS 2nd Day Air ==> $9.03</option><option value="8.34">UPS Ground ==> $8.34</option><option value="9.25">USPS Priority Mail Insured ==> $9.25</option><option value="7.45">USPS Priority Mail ==> $7.45</option><option value="3.20" selected="">USPS First Class ==> $3.20</option>
</select>
</body>
</html>
public static void main(String[] args) throws InterruptedException {ChromeOptions options=new ChromeOptions();options.addArguments("--remote-allow-origins=*");WebDriver webDriver=new ChromeDriver(options);webDriver.get("http://localhost:63342/SeleniumTest/page/test3.html?_ijt=dcl94qtill9arl6odicib469be&_ij_reload=RELOAD_ON_SAVE");WebElement webElement=webDriver.findElement(By.cssSelector("#ShippingMethod"));Select select=new Select(webElement);Thread.sleep(3000);//通過標(biāo)簽 value選擇 select.selectByValue("9.03");Thread.sleep(3000);//通過下標(biāo)選擇,下標(biāo)從零開始select.selectByIndex(2);}
4.4 彈窗操作
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>Title</title>
</head>
<body>
<button onclick="Click()">這是一個彈窗</button>
</body>
<script type="text/javascript">function Click() {let name = prompt("請輸入姓名:");let parent = document.querySelector("body");let child = document.createElement("div");child.innerHTML = name;parent.appendChild(child)}
</script>
</html>
public static void main(String[] args) throws InterruptedException {ChromeOptions options=new ChromeOptions();options.addArguments("--remote-allow-origins=*");WebDriver webDriver=new ChromeDriver(options);webDriver.get("http://localhost:63342/SeleniumTest/page/test4.html?_ijt=e7mju27ab5d214o41bhvcqjf4r&_ij_reload=RELOAD_ON_SAVE");webDriver.findElement(By.xpath("//*[text()=\"這是一個彈窗\"]")).click();Thread.sleep(3000);//alert彈窗取消webDriver.switchTo().alert().dismiss();Thread.sleep(3000);webDriver.findElement(By.xpath("//*[text()=\"這是一個彈窗\"]")).click();Thread.sleep(3000);webDriver.switchTo().alert().sendKeys("軟件測試");Thread.sleep(3000);webDriver.switchTo().alert().accept();}
4.5 文件操作
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>Title</title>
</head>
<body>
<input type="file">
</body>
</html>
public static void main(String[] args) {ChromeOptions options =new ChromeOptions();options.addArguments("--remote-allow-origins");WebDriver webDriver=new ChromeDriver(options);webDriver.get("http://localhost:63342/SeleniumTest/page/test5.html?_ijt=klnnrj3i4pn2rhg6cl7a63qibe&_ij_reload=RELOAD_ON_SAVE");webDriver.findElement(By.cssSelector("input")).sendKeys("E:\\test");}
4.6 quit和close
quit 關(guān)閉了整個瀏覽器,同時會清空瀏覽器的cookie,close關(guān)閉的是get時獲取的頁面.
public static void main(String[] args) throws InterruptedException {ChromeOptions options=new ChromeOptions();options.addArguments("--remote-allow-origins=*");WebDriver webDriver=new ChromeDriver(options);webDriver.get("https://www.baidu.com");webDriver.findElement(By.cssSelector("#s-top-left > a:nth-child(1)")).click();Thread.sleep(3000);//webDriver.close();webDriver.quit();}
?4.7 截圖
public static void main(String[] args) throws InterruptedException, IOException {WebDriver webDriver=new ChromeDriver();webDriver.get("Https://www.baidu.com");webDriver.findElement(By.cssSelector("#kw")).sendKeys("軟件測試");webDriver.findElement(By.cssSelector("#su")).click();Thread.sleep(3000);File file=((TakesScreenshot)webDriver).getScreenshotAs(OutputType.FILE);FileUtils.copyFile(file,new File("E:\\Code\\SeleniumTest\\picture.png"));}
注:截圖操作需要另外引入一個common-io的依賴
Maven Repository: commons-io ? commons-io ? 2.11.0 (mvnrepository.com)