Selenium2 (Java) Selenium common API four

Source: Internet
Author: User
Tags gettext

Webelement Related methods

1. Click Actions

Webelement button =  driver.findelement (by.id ("login")); Button.Click ();

The click () method is called by the element object;

2. Clear operation

Webelement username = driver.findelement (by.id ("Username_input")); Username.clear ();

After the call, the contents of the input box will be emptied;

3. Get the value of the element attribute

<type= "text"  value= ""  autocomplete= "Off" placeholder = "User name" ID = "U" class = "Form-control" onblur = "Checkfailnum ()" name = "username" >

The above code is the user name input box source code, we want to get this "user name" three words need to use;

GetAttribute (java.lang.String name) This method, the code is as follows:

Webelement username = driver.findelement (By.id ("U")); Username.getattribute ("placeholder");

4. Get the text of an element

<type= "text"  value= ""  autocomplete= "Off" placeholder = "User name" ID = "U" class = "Form-control" onblur = "Checkfailnum ()" name = "username" >
Webelement login = driver.findelement (by.id ("loginbtn")); Login.gettext ();

5. Whether the element is displayed

The method has a return value type of Boolean, that is, if the element shows return TRUE if no display returns false;

Webelement login = driver.findelement (by.id ("loginbtn")); login.isdisplayed ();

6. Whether the element is selected

webelement checkbox = Driver.findelement (By.id ("checkbox_id")); checkbox.isselected (); checkbox.isselected () ; // there will be a return value, if checked. Returns True if no check returns false. 

7. Whether the element is enabled

Webelement login = driver.findelement (by.id ("loginbtn")); login.isenabled (); // Returns True if available, False if not available

8. Submit an action

<class= "btn btn-major"  ID= "loginbtn"  type= " Submit "> login </button>
Webelement login = driver.findelement (by.id ("loginbtn")); Login.submit ();

IFRAME Processing

Sometimes when we locate a page element, we find that we can't locate it, and check the locator that we wrote repeatedly without any problems, and the code doesn't have any problems. At this point you will have to look at whether this page element is in an IFRAME, which may be one of the reasons why you cannot find it. If you are looking for an element in the IFRAME in a default content, it must not be found. Conversely, if you look for another IFRAME element in an IFRAME or an element in the default content, it must not be located. The selenium Webdriver provides a way to enter an IFRAME:

Webdriver Org.openqa.selenium.WebDriver.TargetLocator.frame (String nameorid)

It also provides a way to return the default content:

webdriver org.openqa.selenium.WebDriver.TargetLocator.defaultContent () Driver.switchto (). FRAME ("id"); // The ID of the IFRAME is passed in

Return to the previous IFRAME:

Driver.switchto (). Defualcontent ();

Action drop-down selection box

HTML code:

<Selectstyle= "width:75px"onchange= "Change_prodj ()"name= "Province"ID= "Province"><optionvalue= "Ten">A Anhui</option><optionvalue= "One">A Macau</option><optionvalue= " a">B Beijing</option><optionvalue= "+">C Chongqing</option><optionvalue= "+">F Fujian</option><optionvalue= "+">G Gansu</option><optionvalue= " the">G Guangdong</option><optionvalue= "+">G Guangxi</option><optionvalue= "+">G Guizhou</option><optionvalue= "+">H Hainan</option><optionvalue= "+">H Hebei</option><optionvalue= " the">H Henan</option><optionvalue= "+">H Heilongjiang</option></Select>

First, navigate to the Select drop-down box

Webelement element_province = driver.findelement (By.id ("province"));

The element that is anchored to is then passed into the Select

New Select (element_province);

Then select to manipulate the drop-down box

// Select the drop- down box value based on the location of the selected value, starting with 0 // Select the value of the drop-down box according to value, for example, 18 here, the choice is Hainan province. Selectbyvisibletext ("Beijing")// This is based on the visible text to manipulate the drop-down menu, For example, you choose Beijing, then you will find Beijing as a drop-down box

Handling alert

Gets the alert that pops up on the current page

Alert  a= Driver.switchto (). alert ();

After getting to alert, we can use the method provided by alert to get the text on alert, simulate the OK button on the click Alert, simulate the Cancel button on the click Alert, etc.

Get alert Text method: A.gettext ();

Analog Click OK button: A.accept ();

Analog Click cancel button: A.dismiss ();

Processing a new window popup by the browser

We are on a page, clicking on a link does not open the link on the current page but opens a new window to open this page. So how do we jump to the newly opened page to operate the new page? The selenium also provides the corresponding API to handle. First we need to understand that each window has a handle that can be understood as the identifier of the browser window. We can determine the new window based on these identifiers, with the following specific ideas:

Get the current handle first:

String current_handles = driver. Getwindowhandle ();

Gets all window handles after a new window appears

set<string> all_handles = Driver.getwindowhandles ();

Loop judgment, remove the current handle from all handles, and the rest is the new window you want.

iterator<string> it = all_handles.iterator ();  while (It.hasnext ()) {ifcontinue; // jump into a new window Webdriver window = dr.switchto (). Window (It.next ());

Finally, in the new window of the page to do the relevant operation, in the new window operation with the new driver for the page operation, the new driver is window

If you want to go back to the first window, use:

Driver.switchto (). window (current_handles);

Execute JS Script

Sometimes we need JS script to assist us in testing, such as we use JS assignment or use JS to perform click Operations.

Method One:

Declaring a JS script

String js = "alert (\" Hello,this is a alert!\ ")";

Execute JS Script

((Javascriptexecutor) driver). Executescript (JS);

After execution, an alert pops up on the browser that says "Hello,this is a alert!"

The core code is as follows:

New= "alert (\" Hello,this is a alert!\ ")";((javascriptexecutor) driver). Executescript (JS); Thread.Sleep (+);d river.quit ();

Method Two:

This method can be used when some elements are not easy to click, such as the Web page content is too long, the current window is too long, you want to click on those not in the current window can see elements to use this method.
((Javascriptexecutor) driver). Executescript (String js, Object args);
This method has two parameters, the first is the JS script, as for the JS script you like to write a click or input script can be, we here for example click action. The second argument is: the element to be clicked.
For example, I want to click the Search button Baidu search, you can write:
((Javascriptexecutor) driver). Executescript ("Arguments[0].click ();", Driver.findelement (By.id ("su"));
The core code is as follows:

New firefoxdriver ();d river.get("https://www.baidu.com/"= "Arguments[0].click ();" ;d river.findelement (by.id ("kw")). SendKeys ("JAVA"= driver.findelement (by.id ("su"));(( Javascriptexecutor) driver). Executescript (Js,searchbutton); Thread.Sleep (+);d river.quit ();

Wait for element to load

1. Hard wait (not recommended)

Thread.Sleep (int sleeptime);

2. Smart Wait

 Public voidWaitforelementtoload (intTimeOut,Finalby by ) {            Try {        (NewWebdriverwait (Driver, TimeOut)). Until (NewExpectedcondition<boolean>() {             PublicBoolean Apply (webdriver driver) {webelement element=driver.findelement (by); returnelement.isdisplayed ();        }            }); } Catch(TimeoutException e) {assert.fail ("Timeout!!" + timeout + "seconds not found element [" + by + "]", E); }}

3. Set Wait page load complete

int pageloadtime = ten;d river.manage (). Timeouts (). Pageloadtimeout (Pageloadtime, timeunit.seconds);

Simulate keyboard operation

In the Baidu search to enter the keyword Java, and then move the mouse to the search button and the action class to operate the left mouse button to achieve click Search.

Webdriver Driver =Newfirefoxdriver ();//The time to set the waiting page to fully load is 10 seconds, if it is loaded within 10 seconds, the remaining time is not waiting .Driver.manage (). Timeouts (). Pageloadtimeout (10, Timeunit.seconds);d River.get ("https://www.baidu.com/"); by InputBox= By.id ("kw"); by SearchButton= By.id ("su");//instantiating an Action objectActions action =NewActions (driver);//Enter the Java keyword into the input box via the action simulation keyboard, and only enter it using the Perform methodAction.sendkeys (Driver.findelement (SearchButton), "Java"). Perform ();//Mouse Simulation Move to search buttonaction.movetoelement (Driver.findelement (SearchButton)). Perform ();//Analog Click ActionAction.click (). perform (); Thread.Sleep (2000);d river.quit ();

Set browser window size

Window maximization

Driver.manage (). window (). Maximize ();

Specify the setting window size

New dimensiondriver.manage (). window (). setSize (d);

Specify where the window appears in the screen

New Point (page);d river.manage (). window (). SetPosition (p);

Selenium2 (Java) Selenium common API four

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.