selenium code to select radio button - selenium

Am doing automation tesing using selenium, i need help in regarding how to select radio button.If possible help me with selenium java code.

Assuming you have selenium set up its just:
selenium.click('radio button locator');
You may want to look at the selenium javadoc http://release.seleniumhq.org/selenium-remote-control/0.9.2/doc/java/com/thoughtworks/selenium/Selenium.html

click > xpath=(//input[#type='checkbox'])[position()=1]
click > xpath=(//input[#type='checkbox'])[position()=2]
click > xpath=(//input[#type='checkbox'])[position()=3]
click > xpath=(//input[#type='checkbox'])[position()=4]
etc ...
use this commands to select random and any radio button

public class radioExamJavaScr {
public static void main(String[] args) throws IOException {
WebDriver driver = new FirefoxDriver();
EventFiringWebDriver dr = new EventFiringWebDriver(driver);
dr.get("http://www.makemytrip.com/");
dr.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
((JavascriptExecutor)dr).executeScript("document.getElementById('roundtrip_r').click();");
WebElement one_way = (WebElement)((JavascriptExecutor)dr).executeScript("return document.getElementById('oneway_r') ;");
System.out.println(one_way.isSelected());
WebElement round_trip = (WebElement)((JavascriptExecutor)dr).executeScript("return document.getElementById('roundtrip_r') ;");
System.out.println(round_trip.isSelected());
}
}
In the above example I am selecting radio button with "ROUND TRIP" using "JavaScript".
The last four lines are to verify and see whether the expected radio button is selected in the page or not.
NOTE: I am giving simple easy solution to solve a problem (selecting a radio) in the choosen webpage. A better code can be written. (user can write a method to accept radio ID and loop through all the existing radio button to see which one of them is selected).

I use this method:
String radioButtonId = "radioButtonId";
selenium.focus("id=" + radioButtonId);
selenium.click("id=" + radioButtonId, "concreteRadioButtonValue");

What you can do is this:
Create a method with a WebElement return type, and use the Method findElement(). Example:
WebDriver test;
test = new FirefoxDriver();
public static WebElement checkAndGet(By b) throws Exception {
return test.findElement(b);
}
Store the WebElement and use the Method click(). Example:
WebElement radiobutton = checkAndGet(By.xpath("//span[#class='label ng-binding']");
radiobutton.click();
Hope this helps!

Test Scenario : Select Gender(Female) radio button
Steps:
Launch new Browser
Open URL http://toolsqa.wpengine.com/automation-practice-form/
Select the Radio button (female) by Value ‘Female’
Code :
public static void main(String[] args) throws InterruptedException {
System.setProperty("webdriver.chrome.driver", "C:\\chromedriver_win32\\chromedriver.exe");
WebDriver driver = new ChromeDriver(); // Step 1 - Launch Browser
driver.get("http://toolsqa.com/automation-practice-form"); // Step 2 - Open Test URL
List<WebElement> rdBtn_Sex = driver.findElements(By.name("sex")); //
int size = rdBtn_Sex.size();
System.out.println("Total no of radio button :"+size);
for (int i=0; i< size; i++)
{
String sValue = rdBtn_Sex.get(i).getAttribute("value"); // Step 3 - 3. Select the Radio button (female) by Value ‘Female’
System.out.println("Radio button Name "+sValue);
if (sValue.equalsIgnoreCase("Female"))
{
rdBtn_Sex.get(i).click();
}
}

What you should do all the time is provide a locator for every object within a page and then use a method.
Like
driver.findElement(By.xpath(//CLASS[contains(., 'what you are looking for')])).click();

Related

Getting error when trying to execute this code for MMT site

I have used the following code.I am getting NoSuchElementException error when I am trying to run this code for make my trip site
public class suggestiveDropdown_MMTsite {
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
System.setProperty("webdriver.chrome.driver", "C:\\Webdriver\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://www.makemytrip.com/");
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
Actions a = new Actions(driver);
WebElement source = driver.findElement(By.id("fromCity"));
a.moveToElement(source).click().build().perform();
a.moveToElement(source).sendKeys("MUM").build().perform();
/*WebDriverWait w = new WebDriverWait(driver,5);
w.until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By.id("react-autowhatever-1")));*/
WebElement dropdown1 = driver.findElement(By.id("react-autowhatever-1-section-0-item-0"));
a.moveToElement(dropdown1).click().build().perform();
WebElement destination = driver.findElement(By.id("toCity"));
a.moveToElement(destination).click().build().perform();
a.moveToElement(destination).sendKeys("DEL").build().perform();
a.moveToElement(dropdown1).click().build().perform();
}
}
You need to re-identify dropdown1 as the second time it appears it's in a different location in the source an a different webelement.
I see your logic and why you think it would work as it has the same ID - but when you use your By you're returning a specific webelement from the DOM. Even though the ID is reused due to whatever javascript magic, the webelement is different (it's in a different position after all).
The two bits I'm talking about....
1/ This part of your code finds the object:
WebElement dropdown1 = driver.findElement(By.id("react-autowhatever-1-section-0-item-0"));
a.moveToElement(dropdown1).click().build().perform();
2/ It is no longer dropdown 1. It has the SAME ID, but it's a different webelement
a.moveToElement(dropdown1).click().build().perform();
Solution here is re-get the element and I suggest to rename it to help clarify the difference. Change your last line to something like this:
WebElement firstItemInToCity= driver.findElement(By.id("react-autowhatever-1-section-0-item-0"));
a.moveToElement(firstItemInToCity).click().build().perform();
I've had another look. This works for me:
driver.get("https://www.makemytrip.com/");
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
//Actions a = new Actions(driver);
//from city:
WebElement source = driver.findElement(By.id("fromCity"));
source.click();
source.sendKeys("MUM");
//select first item in the list
WebElement dropdown1 = driver.findElement(By.id("react-autowhatever-1-section-0-item-0"));
dropdown1.click();
//Get the to city
WebElement destination = driver.findElement(By.id("toCity"));
destination.click();
destination.sendKeys("DEL");
//pick the first item in the list
WebElement firstItemInToCity= driver.findElement(By.id("react-autowhatever-1-section-0-item-0"));
firstItemInToCity.click();
You do not need to use the actions to interact. Using the selenium native interactions seems fine.
I did have increase the implicit timeout as the page is quote slow to load for me.

Find Elements by Xpath not giving the correct element in Selenium Webdriver

In the following example, I have to click only for Jet Airways. It appears that the xpath selected is correct since it gives the right only from the selection.
http://i.imgur.com/8TiOgha.png
However when this same is being pulled by Selenium WebDriver, it says element not visible. But it still gives a Button with zero length text string. as given in watch window.
http://i.imgur.com/jrR0221.png
I would appreciate if anyone can help me to point if any error I am making since I am new to VBA
Not sure if your XPath is correct and is locating the right static element...
You may use this for locating 'Jet Airways'
//label[text()[contains(.,'Jet Airways')]]
Also, using .click(), try clicking on the 'Airlines' dropdown before locating the 'Airlines Dropdown' XPath
//span[#title='Airlines']
Update:
public class SkyScanner
{
static String chkBxXpth = "//label[#class='dropdown-item cfx']/input[#checked]";
public static void main(String[] args) throws InterruptedException
{
WebDriver driver = new FirefoxDriver();
Actions actions = new Actions(driver);
WebDriverWait wait = new WebDriverWait(driver, 30);
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS);
driver.get("http://skyscanner.cntraveller.com/en-GB/flights#/result?originplace=AUH&destinationplace=LHR");
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//span[#title='Airlines']")));
driver.findElement(By.xpath("//span[#title='Airlines']")).click();
List<WebElement> chkBx = driver.findElements(By.xpath(chkBxXpth));
for(WebElement i : chkBx)
{
actions.moveToElement(i).click().perform();
}
driver.findElement(By.xpath("//label[text()[contains(.,'Jet Airways')]]")).click();
}
}

How to select a item from drop-down, with select class name

How to select a value from Drop-Down in DHTML Grid Using Selenium WebDriver?
enter image description here
By Double click in UMO Column, a drop-down will be seen.
I need to pick a item from that drop-down. But locator is unable to find the Drop-Down.
I am able to double click the field, not able to proceed after that(i.e., Control is not able to locate the drop-down).
Through Firebug, it is shown "Select Class"..
Is there any work around in selenium webdriver to select the item from that drop-down...?
Will be very helpful if u share idea regarding this.
new SelectElement(driver.FindElement(By.ClassName("<className>"))).SelectByIndex("");
new SelectElement(driver.FindElement(By.ClassName("<className>"))).SelectByText("");
new SelectElement(driver.FindElement(By.ClassName("<className>"))).SelectByValue("");
Here is the example code that may help. Create a instance of Select Class from WebElement.
public static void main(String[] args){
WebDriver driver = new FirefoxDriver();
driver.get("http://www.w3schools.com/tags/tryit.asp?filename=tryhtml_select");
driver.switchTo().frame(driver.findElement(By.id("iframeResult")));
WebElement elem = driver.findElement(By.tagName("select"));
Select se=new Select(elem);
se.selectByIndex(3);
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
driver .close();
}
WebElement element = driver.findElements(By.xpath("//*[#id=\"institutionName\"]/option"));
Select select = new Select(element);
select.selectByVisibleText("value");
//select.selectByIndex(0);
//select.selectByValue("1");

wait on handler registering - selenium

There is a html page with button, and my selenium test is testing, that there is an action executed, when the button is clicked.
The problem is, that it looks like the click happens before the javascript is executed - before the handler is bound to the page. The consequence is, that the selenium test will click on the button, but no action happens.
I can solve this problem by repeatedly trying to click and then observe, if the desired action happened (some element is present on page, typically). I'd like to hear that there are some more elegant solutions...
There is no clear way to say "wait until element X has such-and-such handler"; this is a limitation of JavaScript and the DOM (see for example Get event listeners attached to node using addEventListener and jQuery find events handlers registered with an object), and for that matter a selenium Expected Condition can't be created, at least not trivially.
I've resorted to time.sleep(0.5).
You can write some logic to handle this.
I have write a method that will return the WebElement and this method will be called three times or you can increase the time and add a null check for WebElement
Here is an example
public static void main(String[] args) {
WebDriver driver = new FirefoxDriver();
driver.get("https://www.crowdanalytix.com/#home");
WebElement webElement = getWebElement(driver, "homekkkkkkkkkkkk");
int i = 1;
while (webElement == null && i < 4) {
webElement = getWebElement(driver, "homessssssssssss");
System.out.println("calling");
i++;
}
System.out.println(webElement.getTagName());
System.out.println("End");
driver.close();
}
public static WebElement getWebElement(WebDriver driver, String id) {
WebElement myDynamicElement = null;
try {
myDynamicElement = (new WebDriverWait(driver, 10))
.until(ExpectedConditions.presenceOfElementLocated(By
.id(id)));
return myDynamicElement;
} catch (TimeoutException ex) {
return null;
}
}

selenium span link li not working

I am new to selenium. I am practicing to write a test case on http://www.countdown.tfl.gov.uk. Below are the steps I followed:
a) I opened the browser to selenium Web Driver
b) Found the search text Box and enter H32 and clicked on search button to selenium.
Till this part it works fine.
Now on the page I am actually getting two records on the left side of the page under the search. I am actually trying to click on the first one i.e. "Towards Southall,Townhall" link. Nothing is happening.
Below is my code:
public class CountdownTest {
#Test
public void tflpageOpen(){
WebDriver driver = openWebDriver();
searchforBus(driver,"H32");
selectrouteDirection(driver)
}
//open the countdowntfl page
private WebDriver openWebDriver(){
WebDriver driver = WebDriverFactory.getWebDriver("FireFox");
driver.get("http://www.countdown.tfl.gov.uk");
return driver;
}
private void searchforBus(WebDriver driver,String search){
WebElement searchBox = driver.findElement(By.xpath("//input[#id='initialSearchField']"));
searchBox.sendKeys(search);
WebElement searchButton = driver.findElement(By.xpath("//button[#id='ext-gen35']"));
searchButton.click();
}
private void selectrouteDirection(WebDriver driver){
WebElement towardssouthallLink= driver.findElement(By.xpath("//span[#id='ext-gen165']']"));
((WebElement) towardssouthallLink).click();
}
}
Please help me.
Thanks.
Since you are getting NoSuchElement Exception now, you may try the following code with the usage of WebDriver explicit wait.
WebDriverWait wait = new WebDriverWait(driver, 15);
WebElement towardssouthallLink = wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("(//*[#id='route-search']//li/span)[1]")));
towardssouthallLink.click();
Or WebDriver implicit wait
WebDriver driver = WebDriverFactory.getWebDriver("FireFox");
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
driver.get("http://www.countdown.tfl.gov.uk");
Tips:
The search results need some time to be retrieved, so please use Explicit wait or Implicit wait.
Don't use locators like span[#id='ext-gen165'], they are ExtJs auto generated.
In this case, css selector can also be used: #route-search li:nth-of-type(1) > span
You aren't calling selectrouteDirection.
You probably want:
#Test
public void tflpageOpen(){
WebDriver driver = openWebDriver();
searchforBus(driver,"H32");
selectrouteDirection(driver);
}
You also don't need to cast here:
((WebElement) towardssouthallLink).click();
It's already a WebElement anyway.
I found that id for those links are dynamically generated. ids are of the form 'ext-genXXX' where XXX is number which is dynamically generated hence varies each time.
Actually, you should try with linkText:
For 'Towards Southall, Town Hall'
driver.findElement(By.linkText("Towards Southall, Town Hall")).click
For 'Towards Hounslow, Bus Station'
driver.findElement(By.linkText("Towards Hounslow, Bus Station")).click
Here is a logic:
Get all elements which have id starts with 'ext-gen' & iterate over it & click on link with matching text. Following is Ruby code(sorry, I don't know Java well):
links = driver.find_elements(:xpath, "//span[starts-with(#id, 'ext-gen')]")
links.each do |link|
if link.text == "Towards Southall, Town Hall"
link.click
break
end
end