In the Previous Tutorial, we wrote a script where we located all elements in Automation Practice page on which we wanted to perform some actions. We explored the following –
- Method to find an element
- Different WebDriver locators to pass as a parameter to find an element –
- linkText
- id
- className
- xpath
- cssSelector
- name
- partialLinkText
- tagName
In this tutorial, we would continue that script and will learn to perform actions on those elements.
If you followed the Previous Tutorial correctly you should have following lines of code by now –
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.By;
public class SubmitForm {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "C:\\teachmeselenium\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("https://cosmocode.io/automation-practice/");
WebElement lnkReload = driver.findElement(By.linkText("Click here to reload this page"));
WebElement inpFirstName = driver.findElement(By.id("firstname"));
WebElement inpLastName = driver.findElement(By.className("lastname"));
WebElement rdoGender = driver.findElement(By.xpath("//input[@value='Male']"));
WebElement chkLanguage=driver.findElement(By.cssSelector("input[value=java]"));
WebElement lstAge = driver.findElement(By.name("age"));
WebElement btnSubmit = driver.findElement(By.id("submit_htmlform"));
WebElement lnkPartialText = driver.findElement(By.partialLinkText("i-wont-change"));
}
}
from selenium import webdriver
chrome_driver_path = "C:\teachmeselenium\chromedriver.exe"
driver = webdriver.Chrome(chrome_driver_path)
driver.maximize_window()
driver.get("https://cosmocode.io/automation-practice");
reload = driver.find_element_by_link_text("Click here to reload this page")
first_name = driver.find_element_by_id("firstname"))
last_name = driver.find_element_by_class_name("lastname")
gender = driver.find_element_by_xpath("//input[@value='Male']")
language=driver.find_element_by_css_selector("input[value=java]")
age = driver.find_element_by_name("age")
submit = driver.find_element_by_id("submit_htmlform")
partial_link_text = driver.find_element_by_partial_link_text("i-wont-change"))
Please keep opened Automation Practice page in a new browser window. We are going to perform actions on its elements that we located as per above lines of codes.
click() Method – Clicking on a link
- Let us start our automation activity by clicking on the link – ‘Click here to reload this page’. It is located at the beginning of the form on the page.
- If you remember we already got that element – ‘lnkReload’ in the above code snippet.
- This is how we can perform click operation on that element:
lnkReload.click();
reload.click()
Let us insert the above line of code after the code-block that finds that element by calling findElement on lnkReload.
sendKeys() Method – Typing text into an input box
- As we can see we have two input boxes on the page – First Name and Last Name field.
- We have located First Name and Last Name elements that is referred by
inpFirstName
andinpLastName
WebElement
in the Previous Tutorial. - This is how we can ask WebDriver to type some text into an input box:
inpFirstName.sendKeys("TestFirstName"); inpLaststName.sendKeys("TestLastName");
first_name.send_keys("TestFirstName") last_name.send_keys("TestLastName")
- The sendKeys() method takes a String argument that it types into the target input-box.
- Let us insert above lines of code after the code where we located these WebElement –
inpFirstName
,inpLastName
Select Radio item
- As we can see we had located the target radio item that is referred by
rdoGender
WebElement
- For selecting a radio item we just need to perform click operation on it.
rdoGender.click();
gender.click()
Let us insert above lines of code after the code where we located that rdoGender WebElement.
Selecting an item from the drop-down list
- First, we need to locate that element as we have done so far.
- Next, we need to create an object of Select and pass the element found in the previous step.
- Finally, we will use that Select object to select an item from the list.
In the Automation Practice page, there is a drop-down list to select ‘Age’.
We already have a WebElement that refers to that element – lstAge
. Now we will instantiate (create an object of) Select and pass the WebElement that we got in the previous step.
Select selectAge = new Select(lstAge);
Holy Shit. eclipse is showing some error for Select.
Why don’t you move the mouse over the red line for both Select keyword and check if eclipse is suggesting you something? Let me guide you through a screenshot:
from selenium.webdriver.support.ui import Select
select = Select(age);
- Next, we will use
selectAge
object to select age. - Inspect the Select box. As we can see this object has only tag ‘select’. It doesn’t have any properties like id, class, name etc
<select name="age">
<option value="Yet to born">Not Born</option>
<option value="Under 20">Under 20</option>
<option value="20 to 29">Under 30</option>
<option value="30 to 39">Under 40</option>
<option value="40 to 50">Under 50</option>
<option value="Over 50">Above 60</option>
<option value="Ghost">Not Defined</option>
</select>
selectByVisibleText
selectAge.selectByVisibleText("Under 30");
select.select_by_visible_text("Under 30")
selectByValue
selectAge.selectByValue("20 to 30");
select.select_by_value("20 to 29")
selectByIndex
selectAge.selectByIndex(2); //Index starts from 0
select_by_index(2) #Index starts from 0
Assignment for you:
- Try to get all options in the list box and print them to console.
- Verify the selected option.
Clicking on a Button
- We have filled the form. Now its time to submit it.
- As we can see there is a ‘Submit’ button. We already have
btnSubmit
element from the Previous Tutorial.
btnSubmit.click();
btnSubmit.click()
Let us include the above line of code after the line where we refer that WebElement btnSubmit
.
Are you nuts? There is one more item on the page. Check next to the ‘Submit’ button there is a link with link text some-random-text-xyz-GoToHomepage-some-random-digit-123
.
Oh yeah… I guess we referred that WebElement by lnlPartialText
. Let us click on it:
driver.findElement(By.partialLinkText("GoToHomepage")).click();
driver.find_element_by_partial_link_text("GoToHomepage")).click()
Oh, my goodness. You seem to have merged two lines of code into one. Earlier in the first line, we used to get the WebElement and then in the next line we performed the action on it.
Yes, buddy. We can do this way as well. In fact, this is the conventional way. Why don’t you try this for all steps?
- We are done with scripting. Let us
quit()
the driver at the end of the code so that it closes the browser once the execution is over.
Complete Code
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.Select;
public class ScriptClass {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "C:\\teachmeselenium\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("https://cosmocode.io/automation-practice");
WebElement lnkReload;
lnkReload = driver.findElement(By.linkText("Click here to reload this page"));
lnkReload.click();
WebElement inpFirstName = driver.findElement(By.id("firstname"));
inpFirstName.sendKeys("TestFirstName");
WebElement inpLastName = driver.findElement(By.className("lastname"));
inpLastName.sendKeys("TestLastName");
WebElement rdoGender = driver.findElement(By.xpath("//input[@value='Male']"));
rdoGender.click();
WebElement chkLanguage=driver.findElement(By.cssSelector("input[value=java]"));
chkLanguage.click();
WebElement lstAge = driver.findElement(By.name("age"));
Select selectAge = new Select(lstAge);
selectAge.selectByVisibleText("Under 30");
driver.findElement(By.id("submit_htmlform")).click();
driver.findElement(By.partialLinkText("i-wont-change")).click();
driver.quit();
}
}
from selenium import webdriver
chrome_driver_path = "C:\teachmeselenium\chromedriver.exe"
driver = webdriver.Chrome(chrome_driver_path)
driver.maximize_window()
driver.get("https://cosmocode.io/automation-practice");
reload = driver.find_element_by_link_text("Click here to reload this page")
reload.click()
first_name = driver.find_element_by_id("firstname"))
first_name.send_keys("TestFirstName");
last_name = driver.find_element_by_class_name("lastname")
last_name.send_keys("TestLastName");
gender = driver.find_element_by_xpath("//input[@value='Male']")
gender.click();
language=driver.find_element_by_css_selector("input[value=java]")
language.click();
age = driver.find_element_by_name("age")
select = Select(age);
select.select_by_visible_text("Under 30")
submit = driver.find_element_by_id("submit_htmlform")
submit.click()
partial_link_text = driver.find_element_by_partial_link_text("i-wont-change")
driver.find_element_by_partial_link_text("GoToHomepage")).click();
All set dude. Save this project and run it.
Take help from This Previous Tutorial if you missed how to run a Java Project.
Great. You made my life easier by demonstrating all WebDriver locators.
Wait, buddy. I rarely spoon-fed. There is one more WebDriver locator that I deliberately skipped – tag name
. Why don’t you try to google it?
Try to figure out a use case where you can use it and write the code.
Summary
We learned about all 8 WebDriver locators in this and Previous Tutorial –
- linkText
- id
- className
- xpath
- cssSelector
- name
- partialLinkText
- tagName
We also learned to perform the following operations on elements –
- click
- sendKeys
- select
We are done with automating user interactions. I would strongly recommend not to move forward until you are 100% comfortable with this concept and syntax. You would be spending most of your Selenium time dealing with it.
One of the major reason for automation scripts failure is due to synchronization issues. We will handle it by using Waits in the Next Tutorial.
// Below code contains the assignment + new things which i have tried in the form of comments
// your tutorials gives me lot of satisfaction
// there are some questions at the end please do answer them
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
public class ScriptClass {
public static void main(String[] args) {
// TODO Auto-generated method stub
WebDriver driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.get("http://www.cosmotechies.com/teachmeselenium/p/automation-practice.html");
// selecting by ID
WebElement inpFrstNme = driver.findElement(By.id("firstname"));
inpFrstNme.sendKeys("www.udzial.com");
// selecting by xpath – class
//WebElement inpLstNme = driver.findElement(By.xpath("//input[@class='lastname']"));
// selecting by xpath – css
WebElement inpLstNme = driver.findElement(By.cssSelector("input.lastname"));
// selecting by direct className
//WebElement inpLstNme = driver.findElement(By.className("lastname"));
inpLstNme.sendKeys("Udzial Means Share");
// selecting by xpath
WebElement gndr = driver.findElement(By.xpath("//input[@value='Male']"));
//selecting the first occurence of the element as Radio is common for female/male/notknown
// so this will pick the first one = female
//WebElement gndr = driver.findElement(By.xpath("//input[@type='Radio']"));
gndr.click();
// selecting by name
//Assignment 1 <————-
//WebElement lnguage = driver.findElement(By.name("language_c"));
//WebElement lnguage = driver.findElement(By.name("language_java"));
//WebElement lnguage = driver.findElement(By.name("language_vbs"));
WebElement lnguage = driver.findElement(By.name("language_c#"));
lnguage.click();
WebElement age = driver.findElement(By.name("age"));
Select selectAge = new Select(age);
// For selecting any particular option
//selectAge.selectByVisibleText("Under 20");
// for selecting a particular index;
//selectAge.selectByIndex(5);
// Foe selecting by value it may or may not be visible to you
selectAge.selectByValue("Ghost");
WebElement sbmt = driver.findElement(By.xpath("//input[@name='submit']"));
sbmt.click();
// Trying by partial link text
//WebElement home = driver.findElement(By.partialLinkText("Home"));
// Trying by actual complete Linktext
WebElement home = driver.findElement(By.linkText("xyzHome123"));
home.click();
}
}
//q1) whats the purpose of assignment 1 ,, i mean it was just changing name,, may be your expectations are different, can you please let me know ?
// q2) please pay attention to my code and if any mistake or any new things i can try please let me know..because if something is wrong i need to correct it
//q3) i think there is a typo after step 16 inpFirstName.submit();…. it should not be inpFirstName ?
//Assignment 3 will do soon , please change the color to black(text) from blue if possible,, and nice concept of creating the practise link in site
//regards
//Gaurav khurana
//www.udzial.com
//Udzial Means Share
q1)assignment 1 was just to check if readers are not getting addicted to spoonfed and can update the code on their own.
q2)Why dont you put validation point after clicking submit to make sure form has been submitted. use inpFirstname.getAttribute("value") to make sure it is now empty.
q3) that is updated now.
Re font color – I have been doing research for long and trying new designs at frequent intervals. For now I have chooses blue theme. I may change it later.
Hi – I am trying to automate login into Facebook and then sending message:
I have successfully logged into the page and opened the message window, now I am not able to run successfully the cript to write in the To field and sending the message:
Do I require to use switchTo() and then search for iframe, alert, window?
well i cannot say that unless i see the source code. Why don't you inspect source code of message box and look closely if it is inside any iframe or frame tag… If that is the case then you would need to switch to it. It may also happen that due to synchronization issues the message box is coming late but your code is trying to work on that. When you are trying to do sendKeys() in the To field what error it is throwing?
Here;s the code:
I have tried to analyse the HTML code however could not locate any frame.
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
public class manaliFacebook {
public static void main(String[] args) {
WebDriver driver = new FirefoxDriver();
driver.get("http://www.facebook.com");
driver.manage().window().maximize();
driver.findElement(By.xpath("//input[@id='email']")).sendKeys("abc@gmail.com");
driver.findElement(By.xpath("//input[@id='pass']")).sendKeys("xxx");
driver.findElement(By.xpath("//input[@id='u_0_n']")).click();
System.out.print("Manali logged in.");
driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
driver.findElement(By.xpath("//*[@id='fbMessagesJewel']/a")).click();
driver.findElement(By.xpath("//*[@id='u_0_2']")).click();
driver.findElement(By.xpath("//*[@id='fbMessagesJewel']/a")).click();
//driver.switchTo().
//Alert alert = driver.switchTo().alert();
//String strAlertText = alert.getText();
//System.out.println(strAlertText);
driver.findElement(By.xpath("//*[@id='u_0_50']/div/div/div[1]/div/div[1]")).sendKeys("Sender's Name");
driver.findElement(By.xpath("//*[@id='u_0_50']")).sendKeys("This is sent through automation");
driver.findElement(By.id("elementid")).sendKeys(Keys.ENTER);
}
}
And the exceptions says that it is "Unable to locate element: {"method":"xpath","selector":"//*[@id='u_0_50']/div/div/div[1]/div/div[1]"}
Command duration or timeout: 63 milliseconds"
Can you please double check highlighting that element using Selenium IDE – //*[@id='u_0_50']/div/div/div[1]/div/div[1] … If it is getting highlighted then there must be either sync issue or you need to check carefully in the souce code for frame/iframe. If Selenium IDE is also not able to highlight it, there is issue with the xpath.. you need to construct it correctly.
Hi Shadab Ansari,
for this html code snippet :
tag(input type="Checkbox")
C++
This command is failing
//input[contains(text(),'C++')]
Where I am going wrong ?
Regards,
Bharathkumar AV
Here's the code. A bit modified 🙂
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;
public class PracticeClass {
public static void main(String[] args) {
WebDriver driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.get("http://www.cosmotechies.com/teachmeselenium/p/automation-practice.html");
WebElement inpFirstName = driver.findElement(By.id("firstname"));
inpFirstName.sendKeys("TestFirstName");
WebElement inpLastName = driver.findElement(By.className("lastname"));
inpLastName.sendKeys("TestLastName");
WebElement rbGender = driver.findElement(By.xpath("//input[@value='Male']"));
rbGender.click();
WebElement cbLang = driver.findElement(By.xpath("//input[@value='java']"));
cbLang.click();
WebElement cbSecondLang = driver.findElement(By.xpath("//input[@value='c']"));
cbSecondLang.click();
WebElement lstAge = driver.findElement(By.name("age"));
Select selectAge = new Select(lstAge);
selectAge.selectByVisibleText("20 to 29");
File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
File result = new File("D:\Selenium\scr\Submit2.png");
try {
FileUtils.copyFile(scrFile, result);
} catch (IOException e) {
e.printStackTrace();
}
driver.findElement(By.id("submit_htmlform")).click();
driver.findElement(By.partialLinkText("GoToHomepage")).click();
File scrFile2 = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
File result2 = new File("D:\Selenium\scr\Homepage.png");
try {
FileUtils.copyFile(scrFile2, result2);
} catch (IOException e) {
e.printStackTrace();
}
driver.quit();
}
}
Great job 🙂 … +1 for page screenshot implementation
Thank you for great tutorials 🙂
Done 🙂
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;
public class automateme {
public static void main(String[] args) {
// TODO Auto-generated method stub
WebDriver Driver= new FirefoxDriver();
Driver.manage().window().maximize();
Driver.get("http://teachmeselenium.ottomators.com/p/automation-practice.html"😉 ;
//WebElement linksignon= Driver.findElement(By.linkText("Sign in"));
//linksignon.click();
WebElement inpusername=Driver.findElement(By.id("firstname"));
inpusername.sendKeys("saurabh");
WebElement inplastname= Driver.findElement(By.xpath("//input[@class='lastname']"));
inplastname.sendKeys("xyz");
WebElement btngender=Driver.findElement(By.xpath("//input[@value='Male']"));
btngender.click();
WebElement chklanguage=Driver.findElement(By.xpath("//input[@value='java']"));
chklanguage.click();
WebElement chklanguage2=Driver.findElement(By.xpath("//input[@value='vbscript']"));
chklanguage2.click();
WebElement lstAge = Driver.findElement(By.name("age"));
Select selectAge = new Select(lstAge);
selectAge.selectByVisibleText("20 to 29");
WebElement btnsubmit= Driver.findElement(By.cssSelector("input[name=submit]"));
btnsubmit.click();
Driver.findElement(By.partialLinkText("GoToHomepage")).click();
Driver.quit();
}
Hi Shadab,
I was trying to write code for ‘Create Account’ for gmail.However I am getting error for the code given in comment on selecting month,day and year.Please help me.
package Practise;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;
//import org.openqa.selenium.ElementNotVisibleException;
public class GmailSelenium {
public static void main(String[] args) {
// TODO Auto-generated method stub
WebDriver driver = new FirefoxDriver();
driver.get(“https://accounts.google.com/”);
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(100, TimeUnit.SECONDS);
WebElement element = driver.findElement(By.linkText(“Create account”));
element.click();
WebElement FirstName = driver.findElement(By.cssSelector(“input#FirstName”));
FirstName.sendKeys(“Pranshi”);
WebElement LastName = driver.findElement(By.xpath(“//input[@id=’LastName’]”));
LastName.sendKeys(“Gupta”);
WebElement GmailAdd = driver.findElement(By.name(“GmailAddress”));
GmailAdd.sendKeys(“Pranshi18132”);
WebElement Paswd = driver.findElement(By.xpath(“//input[starts-with(@type,’passw’)]”));
Paswd.sendKeys(“Priya@123”);
WebElement ConfPaswrd = driver.findElement(By.name(“PasswdAgain”));
ConfPaswrd.sendKeys(“Priya@123”);
/*WebElement Month = driver.findElement(By.xpath(“//div[starts-with(@class,’goog-inline-block’)]”));
Select mnth = new Select(Month);
mnth.selectByVisibleText(“January”);
WebElement Day = driver.findElement(By.cssSelector(“span#birthday-placeholder”));
Day.sendKeys(“12”);
WebElement Year = driver.findElement(By.xpath(“//span[starts-with(@class,’placeholder’)]”));
Year.sendKeys(“1980”);
WebElement chkbox = driver.findElement(By.cssSelector(“input[value=yes]”));
chkbox.click(); */
}
}
Priyanka, the Month field looks like a dropdown list. But if we look closely at the source code we would find it doesn’t have ‘SELECT’ tag. It has a ‘DIV’ tag. So normal select wont work here.
First we would need to click on that Month element to expand it.
driver.findElement(By.id(“BirthMonth”).click()
and then click on the list item element to select month.
driver.findElement(By.xpath(“//div[@class=’goog-menuitem-content’ and text()=’April’]”).click()
I’ve not tested this code but the logic would be the same.
All,
Please note that the Automation Practice page has moved to the following URL:
http://www.teachmeselenium.blogspot.co.uk/p/automation-practice.html
Many thanks for everything my friend Shadab!
Thanks a lot, Ola Akin for pointing it out.
Actually a few months back we moved the website to different hosting. Unfortunately, some of the links are still left outdated. Updated link is http://www.cosmocode.io/automation-practice/