First, open the browser chrome
1. Install the chrome browser
2. Drive the download control chrome
and chromedriver chrome version of the correspondence and Download
https://blog.csdn.net/huilan_same/article/details/51896672
Storage path:
/ project name /src/main/resources/selenium/driver/chromedriver.exe
3. Download selenium jar package
Add pom.xml dependency
<project>
<dependencies>
<!--selenium框架 --> <dependency> <groupId>org.seleniumhq.selenium</groupId> <artifactId>selenium-java</artifactId> <version>2.50.0</version> </dependency> <!--testNG测试框架 --> <dependency> <groupId>org.testng</groupId> <artifactId>testng</artifactId> <version>6.8</version> </dependency> </dependencies> </project>
4. New java class, start a browser
Since writing class -> selenium -> chromedriver.exe -> chrome browser
//此处src前面没有"/",说明是相对工程根目录的路径
System.setProperty("webdriver.chrome.driver",
"src/main/resources/selenium/driver/chromedriver.exe");
WebDriver driver = new ChromeDriver();
If you want to maximize the window, first set the parameters passed at boot time
//设置环境变量,指定chromedriver的路径
System.setProperty("webdriver.chrome.driver",
"src/main/resources/selenium/driver_v236_63_65/chromedriver.exe");
//设置浏览器的参数
ChromeOptions options = new ChromeOptions(); //最大化浏览器 options.addArguments("--test-type", "--start-maximized"); //指定浏览器位置 //options.setBinary("C:/XXXXXXX/chrome.exe"); //打开浏览器 WebDriver driver = new ChromeDriver(options);
Common causes of error:
- Browser version inconsistencies and chromedriver
- Firewall preventing access chrome browser, turn off the firewall
5. Close the browser
//先线程休眠3秒,便于观察,然后才关闭,不然启动就关闭像闪退
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block e.printStackTrace(); } //关闭浏览器,driver.close()是关闭当前窗口 driver.quit();
sleep () method:
public static void sleep(int millis) { try { Thread.sleep(millis); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
Second, the address bar and navigation (forward, back, refresh)
1. get () method to open
driver.get("http://www.baidu.com");
2. navigate (). To () opens
driver.navigate().to("http://www.dangdang.com");
3. navigate navigation
// 1. 先打开一个界面
driver.navigate().to("http://www.baidu.com");
//2. to()方法再打开另一个界面
driver.navigate().to("http://www.dangdang.com");
sleep(2000); //3. back()回退 driver.navigate().back(); sleep(2000); //4. forward()前进 driver.navigate().forward(); sleep(2000); //5. refresh()刷新 driver.navigate().refresh();
Three, four common way to position elements
Element contains information about:
- label
- Attributes
- content
- position
1. Press id attribute positioning element
WebElement alertButton = driver.findElement(By.id("alertButtonId"));
2. Location attribute name element
WebElement alertButton = driver.findElement(By.name("alertButtonName"));
3. class positioning element
WebElement buttons = driver.findElements(By.className("alertButtonClass"));
4. Use targeting xpath
1) the object of automated processing: tag (also called element)
java | html |
---|---|
WebElement element class | Tag (e.g., html, body, head, table, input, tr, alert pop-up box and the like) |
2) Label
- Label name
- Property of the label
- In order to locate the tag attributes: id, name, class, type
- To attribute to generate the interaction effect: triggering event, the method to be executed after the trigger can be specified
- To identify the data: the data tags are described for
2) xpath: Select html tags
symbol | use | Examples |
---|---|---|
/ | Absolute path | /html/body/table/tbody/tr/td/input |
// | relative path | //body/table//input |
Label name | All html tags | //input |
[] | Conditions defining t | //input[@id='xxxid' and @type='button'] |
digital | Designated to match the first few | //input[3] |
@ Attribute name = attribute value | Property conditions defined by | |
function() | Function defined by condition | |
and/or | A plurality of connection conditions |
WebElement alertButton = driver.findElement(
By.xpath("//input[@id='alertButtonId' and @type='button']"));
Basic operation four common elements
0.5 Interface Template
<html>
<head>
<title>导航栏</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> </head> <body> xxxxxx替换元素代码xxxxxxx </body> </html>
1. text text box
interface:
<input type="text" name="edit" id="edit" value="" />
Automation Code
sendkeys () transfer content to fill
WebElement text=
driver.findElement(By.xpath("//input[@type='text' and @id='edit']"));
text.clear();
text.sendKeys("傻不傻?傻!");
2. file upload file
interface:
<input type="file" name="attach[]" />
Automation Code
Find the elements, sendkeys () transfer a file path
WebElement input=
driver.findElement(By.xpath("//input[@type='file' and @name='attach[]']"));
input.clear();
input.sendKeys("C:/HtmlWeb/selenium/html_00_summary.html");
3. radio radio button
interface:
<input type='radio' name="company" value='Baidu' /> <label>百度</label> <br/> <input type='radio' name="company" value="AliBaBa"/> <label>阿里巴巴</label><br/> <input type='radio' name="company" value='Tencent' checked /><label>腾讯</label><br/> <input type='radio' name="company" value='Mi' /> <label>小米</label>
Automation Code
input element type is raidio, the same name composed of multiple radio types of input options, distinguished by value
Select a specific option and select:
WebElement radio=
driver.findElement(
By.xpath("//input[@type='radio' and @name='company' and @value='Mi']"));
radio.click();
All options point again:
List<WebElement> radios=
driver.findElements(By.xpath("//input[@type='radio' and @name='company']"));
for(int i=0;i<radios.size();i++){
WebElement item=radios.get(i);
sleep(1000); }
4. checkbox checkbox
interface:
<input type="checkbox" name="course" value="web" /><label>网络</label><br /> <input type="checkbox" name="course" value="training" /><label>培训</label><br /> <input type="checkbox" name="course" value="friend" /><label>朋友介绍</label><br /> <input type="checkbox" name="course" value="other" /><label>其他方式</label>
Automation Code
input element type is checkbox, the same name composed of multiple checkbox type of input options, distinguished by value
Select a specific one of the options, and select:
WebElement checkbox=
driver.findElement(
By.xpath("//input[@type='checkbox' and @name='course' and @value='web']"));
checkbox.click();
All options are checked:
List<WebElement> checkboxs=
driver.findElements(
By.xpath("//input[@type='checkbox' and @name='course']"));
for(int i=0;i<checkboxs.size();i++){
WebElement item=checkboxs.get(i);
item.click();
sleep(1000); }
5. Time Control
interface:
<input type="date" name="startTime">
Automation Code
JavaScript code to write, then the driver by performing js
js is of a read-only attribute removed (if not set the read-only time is not needed)
js second sentence elements to the set time value attribute value of "2018-04 -10 "
String js="document.getElementsByName('startTime')[0].removeAttribute('readOnly');document.getElementsByName('startTime')[0].setAttribute('value','2018-04-10');";
JavascriptExecutor jsDriver = (JavascriptExecutor) driver;
jsDriver.executeScript(js);
6. button button
interface:
<input type="button" name="promptbutton" value="测试prompt对话框" onclick="confirm('确定提交吗?');" />
Automation Code
Find the elements, click () Click
WebElement button=
driver.findElement(By.xpath("//input[@type='button' and @id='alertButtonId']"));
button.click();
Alert alert=driver.switchTo().alert();
alert.accept();
7. text field
interface:
Multi-line input box multiple columns
<textarea rows="3" ></textarea>
Automation Code
WebElement textarea=driver.findElement(By.xpath("//textarea[@rows='3']"));
textarea.clear();
textarea.sendKeys(“内容”);
8. img pictures
interface:
Clickable image, is the outside layer <a> hyperlinks, just replace the text with a picture
of automated testing, when you want to locate a hyperlink is <a>
<a id='imgA'>
<img src="xxxx"> </a>
Automation Code
- <a> label positioning
- Click on
WebElement img=driver.findElement(By.xpath("//a[@id='imgA']"));
img.click();
7. select selection box
interface:
select tag: define a drop-down box
option option: Define an option, a drop-down box can have many options, i.e., a plurality of option
. 3 for option attributes: index (option number, automatically add the default), the value of the option value, visibleText show text
<select id="Selector">
<option value="apple" >苹果</option> <option value="peach" >桃子</option> <option value="banana" >香蕉</option> <option value="orange">桔子</option> <option value="grape" >葡萄</option> <option value="mango" >芒果</option> </select>
Automation Code
- Go first to select the tab
- Find option tab and select
- Select the select tag to the object packaged (encapsulated find the option select all of the following operations)
- By value, showing text, numbers
WebElement selectEle=driver.findElement(By.xpath("//select[@id='Selector']"));
Select select=new Select(selectEle);
select.selectByIndex(0);
sleep(1000);
select.selectByValue("banana"); sleep(1000); select.selectByVisibleText("桔子"); sleep(1000);
8. a hyperlink
interface:
<a href="http://www.guoyasoft.com">Copyright 2017 guoyasoft</a>
Automation Code
Positioning hyperlinks 3 methods:
- Using xpath
WebElement link=
driver.findElement(By.xpath("//a[@href='http://www.guoyasoft.com']"));
- Use linkText: according to the text of the link an exact match
WebElement link=driver.findElement(By.linkText("Copyright 2017 guoyasoft"));
- Use partialLinkText: Press text link fuzzy matching
WebElement baike=driver.findElement(By.partialLinkText("guoyasoft"));
Click three kinds: 1, the current interface is open; 2, a new tab is opened; a new window opens
Click on: Open the current interface
WebElement link=
driver.findElement(By.xpath("//a[@href='http://www.guoyasoft.com']"));
link.click();
ctrl + shift + click: current browser to open a new tab
Actions actions=new Actions(driver);
actions.keyDown(Keys.SHIFT).keyDown(Keys.CONTROL).click(link).perform();
shift + click: Open a new window (open a new browser)
Actions actions=new Actions(driver);
actions.keyDown(Keys.SHIFT).click(link).perform();
Five, alert frame switching
interface:
<tr>
<td>prompt对话框</td> <td><input type="button" name="promptbutton" value="测试prompt对话框" onclick="clickbutton();" /></td> </tr>
javascript:
function clickbutton() {
var name = prompt("测试prompt对话框", ""); if (name != null && name != "") { //document.write(name); alert(name); } }
Automation Code
WebElement clickOnPrompt = driver.findElement(By
.xpath("//td/input[@name='promptbutton']"));
clickOnPrompt.click();
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Alert prompt = driver.switchTo().alert();
try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } prompt.sendKeys("I love Selenium"); prompt.accept(); try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } Alert afterAccept = driver.switchTo().alert(); afterAccept.accept(); try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); }
Sixth, window switch
interface:
<tr>
<td>超链接</td> <td> <div> <a id="link_baidu" href="https://www.baidu.com">百度</a> </div> <div> <a id="link_jd" href="https://www.JD.com">京东</a> </div> <div> <a id="link_dangdang" href="http://www.dangdang.com/">当当</a> </div> </td> </tr>
Automation Code
Core code:
- driver.getWindowHandle () to get the current window handle
- driver.getWindowHandles () Gets the browser window handles all
- driver.switchTo (). windows (object handle)
- The title of the selected window are judged correct (first handover control, then check KEYWORDS)
public static void switchToWindow(String windowTitle, WebDriver dr) {
// 将页面上所有的windowshandle放在入set集合当中
String currentHandle = dr.getWindowHandle(); Set<String> handles = dr.getWindowHandles(); for (String s : handles) { dr.switchTo().window(s); // 判断title是否和handles当前的窗口相同 if (dr.getTitle().contains(windowTitle)) { break;// 如果找到当前窗口就停止查找 } } }
Practice Test:
- Open the test interface
- Jingdong open, cut back to the original window
- Open Baidu, cut back to the original window
- Open Dangdang, cut back to the original window
private void testWindow(WebDriver driver, TestSelenium3 test) { /* * 第1步:打开测试界面 */ driver.get("http://127.0.0.1:8081/HtmlWeb/selenium/html_00_summary.html"); Actions actions = new Actions(driver); /* * 第2步:点击京东,再切换回原界面 */ WebElement jd = driver.findElement(By.xpath("//a[@id='link_jd']")); //按顺序点,按顺序放 actions.keyDown(Keys.SHIFT).keyDown(Keys.CONTROL).click(jd) .keyUp(Keys.SHIFT).keyUp(Keys.CONTROL).perform(); test.mySleep(1000); //窗口切换到京东,进行操作,此处不做任何操作 switchToWindow("京东", driver); test.mySleep(1000); //切换回原窗口 switchToWindow("selenium", driver); test.mySleep(1000); /* * 第3步:点击百度,再切换回原界面 */ WebElement baidu = driver .findElement(By.xpath("//a[@id='link_baidu']")); actions.keyDown(Keys.SHIFT).keyDown(Keys.CONTROL).click(baidu) .keyUp(Keys.SHIFT).keyUp(Keys.CONTROL).perform(); actions.click(); test.mySleep(1000); switchToWindow("百度一下,你就知道", driver); test.mySleep(1000); switchToWindow("selenium", driver); test.mySleep(1000); /* * 第4步:点击当当,再切换回原界面 */ WebElement dangdang = driver.findElement(By .xpath("//a[@id='link_dangdang']")); actions.keyDown(Keys.SHIFT).keyDown(Keys.CONTROL).click(dangdang) .keyUp(Keys.SHIFT).keyUp(Keys.CONTROL).perform(); actions.click(); test.mySleep(1000); switchToWindow("当当", driver); test.mySleep(1000); switchToWindow("selenium", driver); test.mySleep(1000); }
Seven switching interface framework frame
1. The interface code
1.1 main.html
<html>
<head>
<title>iframe测试界面</title> </head> <frameset rows="15%,75%,*" frameborder="1" framespacing="10"> <frame src="top.html"></frame> <frameset cols="20%,*"> <frame src="left.html"></frame> <frame src="right.html" name="content"></frame> </frameset> <frame src="button.html"></frame> </frameset> </html>
1.2 top.html
<html>
<body>
<!--图片放到webapp/images下面--> <img src="../../images/top.png" width="90%" height="80%"> </body> </html>
1.3 left.html
<html>
<body>
<ul> <li><a href="http://www.baidu.com" target="content">百度</a></li> <li><a href="http://www.jd.com" target="content">京东</a></li> <li><a href="http://www.taobao.com" target="content">淘宝</a></li> <li><a href="http://www.dangdang.com" target="content">当当</a></li> <li><a href="http://www.youku.com" target="content">优酷</a></li> </ul> </body> </html>
1.4 right.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=gb2312" /> <title>管理页面</title> </head> <body>该界面用于展示菜单内容 </body> </html>
1.5 button.html
<html>
<body>
<img src="../../images/button.png" width="90%" height="75%" > </body> </html>
2. frame test code
Step 1: Open the test interface
driver.get("http://127.0.0.1:8081/HtmlWeb/selenium/iframe2/main.html");
Step 2: Locate the left navigation frame box
WebElement leftFrame=driver.findElement(By.xpath("//frame[@src='left.html']"));
Step 3: handover control to the window frame
driver.switchTo().frame(leftFrame);
Content of the test frame box: Step 4
WebElement baidu=driver.findElement(By.xpath("//a[@href='http://www.baidu.com']"));
baidu.click();
test.mySleep(2000);
Step 5: switching back to the original main window of the control window
driver.switchTo().defaultContent();
Step 6: Locate the right window, click on the contents of the connection that is open
WebElement rightFrame=driver.findElement(By.xpath("//frame[@src='right.html']"));
Step 7: switching to the right of the window frame
driver.switchTo().frame(rightFrame);
Step 8: Test the right window
test.mySleep(3000);
WebElement input=driver.findElement(By.xpath("//input[@id='kw']"));
input.clear();
input.sendKeys("果芽软件");
WebElement submit=driver.findElement(By.id("su"));
submit.click();
test.mySleep(2000); //定位超链接元素的专用方法(精确和模糊两种,类似id和name选择器) WebElement baike=driver.findElement(By.linkText("上海果芽软件科技有限公司_百度百科")); //WebElement baike=driver.findElement(By.partialLinkText("果芽软件")); baike.click(); test.mySleep(2000);
Eight, set the interface to load and latency positioning elements
1. thread sleep
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
2. Implicit wait
//设置界面加载等待时间,全局设置,作用于driver,对所有后续界面加载都有效
driver.manage().timeouts().pageLoadTimeout(3000, TimeUnit.MILLISECONDS);
driver.get("http://www.baidu.com");
//设置元素定位超时等待时间,全局设置,作用于driver,对所有后续元素定位都有效
driver.manage().timeouts().implicitlyWait(3000, TimeUnit.MILLISECONDS); WebElement element=driver.findElement(By.xpath("kw"));
3. Display wait
WebDriverWait wait=new WebDriverWait(driver, 2);
wait.until(new ExpectedCondition<Boolean>() {
public Boolean apply(WebDriver d) { boolean loadcomplete = d.findElement(By.xpath("")).isDisplayed(); return loadcomplete; } });
Author: fruit buds software
link: https: //www.jianshu.com/p/bd7db15446ea
Source: Jane book
Jane book copyright reserved by the authors, are reproduced in any form, please contact the author to obtain authorization and indicate the source.