Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Selenium of UI Automation Test (1)-- api commonly used in selenium

2025-02-22 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/03 Report--

Catalogue

1 for browser operation

1.1 Open a browser with webdriver

1.2 maximize browser & close browser

1.3 set browser window size

1.4 Open the test page

1.5 handle new windows that pop up in the browser

2 page element positioning

3 how to operate on page elements

3.1 WebElement related methods

3.2 treatment of iFrame

3.3input box (text field or textarea)

3.4 drop-down selection box (Select)

3.5 single option (Radio Button)

3.6 multiple options (checkbox)

3.7Button (button)

3.8 processing Alert

3.9 upload files

3.9.1 upload method when element tag is Input

3.9.2 upload by operating the desktop browsing window

3.10 Selenium processing HTML5

3.10.1 processing Vedio

3.10.2 processing Canvas

3.11 form (Form)

4 other

4.1 wait for the element to load

4.2 execute JS script

4.3 simulate keyboard operation

1 for browser operation

Return

1.1 Open a browser with webdriver

/ / Open firefox browser: WebDriver driver = new FirefoxDriver (); / / Open IE browser WebDriver driver = new InternetExplorerDriver (); / / Open HtmlUnit browser WebDriver driver = new HtmlUnitDriver (); / / Open chrome browser WebDriver driver = new ChromeDriver ()

1.2 maximize browser & close browser

WebDriver driver = new FirefoxDriver ()

Driver.manage (). Window (). Maximize ()

Driver.close ();-Close the current window, quitting the browser if it's the last window currently open.

Driver.quit ();-Quits this driver, closing every associated window.

1.3 set browser window size

View Code

1.4 Open the test page

Open the test page

Driver.get ("http://www.baidu.com/");"

Driver.navigate () .to ("http://www.baidu.com/");

The / / navigate method produces a Navigator object that encapsulates some navigation-related methods, such as forward and backward

1.5 handle new windows that pop up in the browser

Private static void MutiWindowTest (WebDriver driver)

Throws InterruptedException {

WebDriver newWindow = null

Driver.get ("http://www.hao123.com/");"

/ / browser maximization

Driver.manage (). Window (). Maximize ()

/ / get the current page handle `String current_handles = driver.getWindowHandle (); / / Click the Baidu link driver.findElement (By.xpath ("/ / * [@ data-title=' Baidu']")) .click (); / A new window will open next, get all the window handles Set all_handles = driver.getWindowHandles (); `

/ / Loop judgment, remove the current handle from all handles, and all that is left is the new window you want Iterator it = all_handles.iterator (); while (it.hasNext ()) {if (current_handles = = it.next ()) continue; ```/ / jump into the new window and get the driver-newWindow newWindow = driver.switchTo () .window (it.next ()) of the new window. } / / next, on the new page, that is, Baidu homepage, we enter a java keyword to search Thread.sleep (5000); WebElement baidu_keyowrd = newWindow.findElement (By.id ("kw")); baidu_keyowrd.sendKeys ("java"); Thread.sleep (1000); / / close the current window, mainly using close instead of quite, newWindow.close () Driver.switchTo () .window (current_handles); System.out.println (driver.getCurrentUrl ());} 2 Page element positioning returns Webdriver provides the following two ways to locate page elements, the parameter is the By object, and the most commonly used are By.id and By.name lookups. FindElement locates an element. If no element is found, an exception is thrown: NoSuchElementException findElements locates a group of elements, for example, the following elements need to be located:

/ / By.id

WebElement element = driver.findElement (By.id ("passwd-id"))

/ / By.name

WebElement element = driver.findElement (By.name ("passwd"))

/ / By.xpath

WebElement element = driver.findElement (By.xpath ("/ / input [@ id='passwd-id']"))

/ / By.className

WebElement element = driver.findElement (By.className ("input_class"))

/ / By.cssSelector

WebElement element = driver.findElement (By.cssSelector (".input _ class"))

/ / By.linkText

/ / the popular point is accurate query.

WebDriver driver = new FirefoxDriver ()

Driver.get ("http://www.baidu.com/");"

WebElement element = driver.findElement (By.linkText ("encyclopedia"))

/ / By.partialLinkText:

/ / this method is a fuzzy query.

WebDriver driver = new FirefoxDriver ()

Driver.get ("http://www.baidu.com/");"

WebElement element = driver.findElement (By.partialLinkText ("hao"))

/ / By.tagName

WebDriver driver = new FirefoxDriver ()

Driver.get ("http://www.baidu.com/");"

String test= driver.findElement (By.tagName ("form")) .getAttribute ("name")

System.out.println (test)

3 how to operate on page elements

Return

3.1 WebElement related methods

3.2 treatment of iFrame

Driver.switchTo () .frame ("city_set_ifr"); / / the IDdr.switchTo () .defaultContent () of iframe is passed in; / / if you want to return to the previous default content

3.3input box (text field or textarea)

WebElement element = driver.findElement (By.id ("passwd-id")); element.sendKeys ("test"); / / enter: element.clear () in the input box; / / empty the input box element.getText (); / / get the text content of the input box:

3.4 drop-down selection box (Select)

Select select = new Select (driver.findElement (By.id ("select")

Select.selectByVisibleText ("A")

Select.selectByValue ("1")

Select.deselectAll ()

Select.deselectByValue ("1")

Select.deselectByVisibleText ("A")

Select.getAllSelectedOptions ()

Select.getFirstSelectedOption ()

Example:

Package seleniumAPIDemo;import org.openqa.selenium.By;import org.openqa.selenium.WebDriver;import org.openqa.selenium.firefox.FirefoxDriver;import org.openqa.selenium.support.ui.Select;public class SelectDemo {public static void main (String [] args) throws InterruptedException {WebDriver driver = new FirefoxDriver (); iframeAndSelectTest (driver); driver.quit () } private static void iframeAndSelectTest (WebDriver driver) throws InterruptedException {driver.get ("http://www.2345.com/"); / / browser maximization driver.manage (). Window () .maximize (); / / Click the toggle button driver.findElement (By.id (" J_city_switch ")) .click () / / enter the weather city and select iframe driver.switchTo () .frame ("city_set_ifr"); Thread.sleep (2000) / / then select the city / / locate the province drop-down box Select province = new Select (driver.findElement (By.id ("province")); province.selectByValue ("20"); Thread.sleep (2000) / / location city drop-down box Select city = new Select (driver.findElement (By.id ("chengs")); city.selectByIndex (0); Thread.sleep (2000); / / location area Select region = new Select (driver.findElement ("cityqx")); region.selectByVisibleText ("X New Secret"); Thread.sleep (2000) / / Click the custom button driver.findElement (By.id ("buttonsdm")) .click (); Thread.sleep (2000); / / return the default content driver.switchTo () .defaultContent ();}}

3.5 single option (Radio Button)

WebElement radio=driver.findElement (By.id ("BookMode"))

Radio.click (); / / Select a single option

Radio.clear (); / / clear a single option

Radio.isSelected (); / / determine whether a single option has been selected

3.6 multiple options (checkbox)

WebElement checkbox = driver.findElement (By.id ("myCheckbox."))

Checkbox.click ()

Checkbox.clear ()

Checkbox.isSelected ()

Checkbox.isEnabled ()

3.7Button (button)

WebElement btn= driver.findElement (By.id ("save"))

Btn.click (); / / Click the button

Btn.isEnabled (); / / determine whether the button is enable

3.8 processing Alert

Pop-up dialog box (Popup dialogs)

Alert alert = driver.switchTo () .alert ()

Alert.accept (); / / confirm

Alert.dismiss (); / / cancel

Alert.getText (); / / get text

Example:

Private static void alertTest (WebDriver driver) throws InterruptedException {driver.get ("http://www.w3school.com.cn/tiy/t.asp?f=hdom_alert"); / / browser maximization driver.manage (). Window () .maximize (); / / enter frame driver.switchTo () .frame (" I ")) / / find the button and click the button driver.findElement (By.xpath ("/ / * [@ value=' display message box']"). Click (); Thread.sleep (2000); / / get Alert Alert a = driver.switchTo (). Alert (); / / print out the text content System.out.println (a.getText ()) / / Click OK Thread.sleep (2000); a.accept (); / / if there is a cancel button on the alert, you can use the a.dismiss () code}

3.9 upload files

3.9.1 upload method when element tag is Input

The Upload.html file is as follows:

The code is as follows:

Private static void uploadTest1 (WebDriver driver) throws InterruptedException {/ / Open the uploaded web page-enter the address of upload driver.get ("D:\\ DownLoad\\ UploadTest\\ upload.html") in get; WebElement E1 = driver.findElement (By.id ("fileControl")); Thread.sleep (2000) / / enter the address e1.sendKeys of the file to be uploaded ("D:\ DownLoad\\ UploadTest\\ uploaded file .txt"); Thread.sleep (2000);}

3.9.2 upload by operating the desktop browsing window

Example 2 upload a file

When the upload control is not an input element, but a desktop window, it is not feasible to use Selenium's sendkeys method. You can use autoIt to operate. Please refer to the autoIT for yourself. The specific calls are as follows:

Public void handleUpload (String browser, File file) {String filePath= file.getAbsolutePath (); String executeFile= "D:\\ TestUploadFileWithAutoit\\ UploadFile.exe"; String cmd= "\"+ executeFile+"\ "" + "+"\ "" + browser+ "\"+" + "\" + filePath+ "\"; try {Process p = Runtime.getRuntime (). Exec (cmd); p.waitFor () } catch (Exception e) {e.printStackTrace ();}}

3.10 Selenium processing HTML5

3.10.1 processing Vedio

Private static void html5VedioTest (WebDriver driver) throws InterruptedException {driver.get ("http://videojs.com/"); Thread.sleep (2000); / / find the vedio element WebElement vedio = driver.findElement (By.id (" preview-player_html5_api ")); / / declare the js actuator JavascriptExecutor js = (JavascriptExecutor) driver / / perform a playback operation js.executeScript ("arguments [0] .play ()", vedio) on the element vedio; / / pause Thread.sleep for 5 seconds (5000) in order to observe the effect; / / perform a pause operation js.executeScript on the element vedio ("arguments [0] .pause ()", vedio) / pause Thread.sleep for 2 seconds (2000) to observe the effect; / / perform the playback operation js.executeScript ("arguments [0] .play ()", vedio) on the element vedio; / / pause Thread.sleep for 2 seconds (2000) to observe the effect / / A pair of vedio performs the operation of reloading the video js.executeScript ("arguments [0] .load ()", vedio); / / pauses Thread.sleep (2000) for 2 seconds to observe the effect;}

You need to understand the relevant methods of vedio in html5. You can refer to http://www.w3school.com.cn/tags/html_ref_audio_video_dom.asp.

View Code

3.10.2 processing Canvas

Private static void Html5CanvasTest (WebDriver driver) throws InterruptedException {driver.get ("http://literallycanvas.com/"); Thread.sleep (2000); / / find the canvas element WebElement canvas = driver.findElement (By.xpath (" / / * [@ id='literally-canvas'] / / canvas [1] ")); / / declare an operation class Actions drawPen = new Actions (driver) / / Click and hold the mouse and move drawPen.clickAndHold (canvas) .moveByOffset (20,100) .moveByOffset (100,20). MoveByOffset (- 20,100). MoveByOffset (- 100,20). Release (). Perform (); Thread.sleep (2000);}

3.11 form (Form)

The operation of the element in / / Form is the same as that of other element operations. You can submit the form after the element operation is completed:

WebElement approve = driver.findElement (By.id ("approve"))

Approve.click ()

/ / or

Approve.submit (); / / is only suitable for form submission

4 other

Return

4.1 wait for the element to load

Timeout setting

WebDriver driver = new FirefoxDriver ()

Driver.manage (). Timeouts (). ImplicitlyWait (10, TimeUnit.SECONDS); / / timeout when identifying an element

Driver.manage () .timeouts () .pageLoadTimeout (10, TimeUnit.SECONDS); / / timeout when the page is loaded

Driver.manage () .timeouts () .setScriptTimeout (10, TimeUnit.SECONDS); / / timeout of asynchronous scripts

Hard wait Thread.sleep (int sleeptime); Smart wait settings wait for the page to be loaded private static void waitElementTest (WebDriver driver) {/ / set the time to wait for the page to be fully loaded is 10 seconds. If the page is loaded within 10 seconds, the remaining time is no longer waiting for driver.manage (). Timeouts (). PageLoadTimeout (10, TimeUnit.SECONDS); driver.get ("https://www.baidu.com/"); By inputBox = By.id ("kw"); By searchButton = By.id ("su"); / / Smart wait element loaded intelligentWait (driver, 10, inputBox); / / Smart wait element loaded out intelligentWait (driver, 10, searchButton); / / input content driver.findElement (inputBox) .sendKeys ("JAVA") / / Click to query driver.findElement (searchButton). Click ();} public static void intelligentWait (WebDriver driver,int timeOut, final By by) {try {(new WebDriverWait (driver, timeOut)) .query (new ExpectedCondition () {public Boolean apply (WebDriver driver) {WebElement element = driver.findElement (by)) Return element.isDisplayed ();}} catch (TimeoutException e) {Assert.fail ("timeout!" + timeOut + "seconds later) element [" + by + "]", e);}}

4.2 execute JS script

Summary of js commonly used in selenium

Sometimes we need JS scripts to assist us in testing, such as we use JS assignments or click operations with js. Executing JS script is suitable for some elements that are not easy to click, such as the content of the web page is too long, the current window is too long, you can use this method if you want to click on those elements that can not be seen in the current window.

Private static void runJSTest1 (WebDriver driver) throws InterruptedException {String js = "alert (\" hello,this is an alert!\ ")"; ((org.openqa.selenium.JavascriptExecutor) driver) .executeScript (js); Thread.sleep (2000);} private static void runJSTest2 (WebDriver driver) throws InterruptedException {driver.get ("https://www.baidu.com/"); String js =" arguments [0] .click (); " Driver.findElement (By.id ("kw")) .sendKeys ("JAVA"); WebElement searchButton = driver.findElement (By.id ("su")); ((org.openqa.selenium.JavascriptExecutor) driver) .executeScript (js,searchButton); Thread.sleep (2000);}

4.3 simulate keyboard operation

Sometimes some elements are inconvenient to click or do other operations, at this time, you can use the Actions class provided by selenium, which can simulate some mouse and keyboard operations, such as clicking the right mouse button, left button, moving the mouse and so on. These operations are performed using the perform () method.

Copy the code

Private static void actionsTest (WebDriver driver) throws InterruptedException {/ / sets the time to wait for the page to load completely in 10 seconds. If the page is loaded within 10 seconds, the remaining time is not waiting for driver.manage (). Timeouts (). PageLoadTimeout (10, TimeUnit.SECONDS); driver.get ("https://www.baidu.com/"); By inputBox = By.id (" kw "); By searchButton = By.id (" su ") / / Smart wait element loaded intelligentWait (driver, 10, inputBox); / / Smart wait element loaded intelligentWait (driver, 10, searchButton); / / instantiate action object Actions action = new Actions (driver) / enter the java keyword into the input box through the action simulated keyboard, and enter action.sendKeys (driver.findElement (searchButton), "java") .perform () only if you use the perform method; / / simulate mouse movement to the search button action.moveToElement (driver.findElement (searchButton)). Perform (); / / simulated click operation action.click (). Perform (); Thread.sleep (2000);}

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report