Using Selenium, how to click a radio button based on associated label - c#

I'm using Selenium in C#, and I need to be able to specify which radio button on a website to click based on the text of the label that is associated with that radio button. I need to be able to pass that text in as a parameter. Here is a sample of what the code for the radio buttons looks like (this is for three buttons):
<input id="radSelect152_222_1369" class="bgRadioNotChecked" type="radio" onclick="BGQ.Ajax.SelectAnswer(this, '152','1369','3', '547');" value="1369" onfocus="BGQ.View.setLastElement(true);" name="radSelect152_222">
<label class="inline" for="radSelect152_222_1369">Watermelon</label>
<input id="radSelect152_222_1370" class="bgRadioNotChecked" type="radio" onclick="BGQ.Ajax.SelectAnswer(this, '152','1370','3', '547');" value="1370" onfocus="BGQ.View.setLastElement(true);" name="radSelect152_222">
<label class="inline" for="radSelect152_222_1370">Papaya</label>
<input id="radSelect152_222_1371" class="bgRadioNotChecked" type="radio" onclick="BGQ.Ajax.SelectAnswer(this, '152','1371','3', '547');" value="1371" onfocus="BGQ.View.setLastElement(true);" name="radSelect152_222">
<label class="inline" for="radSelect152_222_1371">Mango</label>
I want to be able to specify "Mango" in an Excel input file (I have all the file input stuff working fine) and have Selenium click the associated radio button. One approach that I read that I've been trying is to do the following:
Find the element that has the target text ("Mango") as its text
Get the FOR attribute from that element
Find the input that has an id equal to that FOR attribute
Click that input element.
Problem is, I'm pretty new to Selenium and can't quite figure the syntax for how to do these four steps. Can someone show me the way, with specific code examples? Also, or alternatively, is there a better/smarter way to do this? If so, please be specific.
I've included here the method I've started to write, in which I pass in the target text. I know it's wrong (especially in the By.XPath part).
public void ClickRadioButtonByLabelText(string labelText)
{
// (1) Find the element that has the label text as its text
IWebElement labelForButton = commondriver.FindElement(By.XPath(//label[text()='labelText']));
// (2) Get the FOR attribute from that element
string forAttribute
// (3) Find the input that has an id equal to that FOR attribute
// (4) Click that input element
}
Thanks.

You have two options.
Option 1 - do it all within a single XPath query
The XPath query would be:
//input[#id=//label[text()='TestCheckBox']/#for]
That is, get input that has an id which comes from the for attribute from a label that has the text of "TestCheckBox"
Option 2 - get the attribute from the label and then find the element in seperate steps
public void ClickRadioButtonByLabelText(string labelText)
{
// (1) Find the element that has the label text as its text
IWebElement labelForButton = commondriver.FindElement(By.XPath("//label[text()='labelText']"));
// (2) Get the FOR attribute from that element
string forAttribute = labelForButton.GetAttribute("for");
// (3) Find the input that has an id equal to that FOR attribute
IWebElement radioElement = commondriver.FindElement(By.Id(forAttribute));
// (4) Click that input element
radioElement.Click();
}

Related

Select from tag type - input dropdown with selenium C# webdriver

How can i get element from below dropdwon, i have used Select command to select dropdowns, but here type is input.
<input class="tp-select-input" autocapitalize="none" autocorrect="off" autocomplete="off" spellcheck="false" data-testid="register-country" value="">
As dropdown you want to select value from is not a select type tag, Selenium Select method wont work on it. You have to follow below steps:
Click on Dropdown / or Arrow
Locate webelement you want to select from dropdown
Use java script executioner to click the option you want to select
Since you have not given complete HTML, below is the dummy code:
driver.FindElement(By.XPath("//input[#data-testid='register-country']")).Click() // Click on dropdown
IJavaScriptExecutor executor = (IJavaScriptExecutor)driver;
executor.ExecuteScript("arguments[0].click();", driver.FindElement(By.XPath("//*[text()='Austria']"))); //You can give more accurate xpath for country you want to select based on other HTML attributes
You can also try with below code
IWebElement element = driver.FindElement(By.ClassName("tp-select-input")); driver.FindElement(By.XPath("//span[text()='Australia']")); element.SendKeys(OpenQA.Selenium.Keys.Down); element.SendKeys(OpenQA.Selenium.Keys.Return);

How to click on the SIGN IN button using Selenium and C#

I am trying to create this simple test where you head to the URL, enter your login credentials and then click the button to sign in. It is doing everything, except for clicking the button. I am trying to doing it by calling up ClassName. Can anyone look at my test and see what I am doing wrong?
public void test_search()
{
var driver2 = new ChromeDriver(#"C:\Users\MyName\Desktop\NUnitTestProject1\NUnitTestProject1\bin\Debug\netcoreapp2.1");
driver2.Navigate().GoToUrl("https://portal.crushdata.com/");
driver2.FindElement(By.Name("Email")).SendKeys("email#email.com");
driver2.FindElement(By.Name("Password")).SendKeys("Password");
driver2.FindElement(By.ClassName("btn bg-teal btn-block btn-lg waves-effect")).Click();
}
This is my classname for my button.
Use CSS selector as shown below:
By.ClassName("btn.bg-teal.btn-block.btn-lg.waves-effect")
Each dot represents a class.
See this page for more info and here is an example from that page:
.name1.name2
Selects all elements with both name1 and name2 set within its class attribute
To click on the SIGN IN button you have to induce WebDriverWait for the desired ElementToBeClickable() and you can use either of the following Locator Strategies:
CssSelector:
new WebDriverWait(driver, TimeSpan.FromSeconds(20)).Until(ExpectedConditions.ElementToBeClickable(By.CssSelector("button.btn.bg-teal.btn-block.btn-lg.waves-effect"))).Click();
XPath:
new WebDriverWait(driver, TimeSpan.FromSeconds(20)).Until(ExpectedConditions.ElementToBeClickable(By.XPath("//button[text()='SIGN IN']"))).Click();
Try making use of the button xpath.
Open the dev tools. Right click on the button you want to be clicked > Select Inspect >Then right click the html in the dev tools window and Copy Xpath from the Copy option.
Then in you code replace FindElement with FindElementByXPath:
driver2.FindElementByXPath("//*xpath/goes/here")).Click();
Given your shared html block, the following XPath will suffice.
//div[contains(#class = "text-center")]//button[contains(#class, 'btn bg-teal btn-block btn-lg waves-effect') and #type = 'submit']
If the driver is still unable to click you should consider the following:
Is the XPath unique? paste the xpath in chrome's devtools search box in the inspect element tab and make sure the provided xpath is targeting the element you are intending. If this is not the case then you should make the xpath more unique.
Is the element in an iframe? if the element is in an iframe the driver won't be able to locate it by default. In such cases you will need to first switch to the iframe and then attempt to locate and interact with the element.
Is the element clickable, visible and enabled? To check these properties first find the element and store in a separate variable and then check the said properties are true.

Selenium with combo box control and select element

The product which I am trying to automate has a customized combo box control from .Net.
The control is of type <input> and I will be able to type n search with the starting letter only.
When I try to access the <select> element using WebDriver , it says that the operation cannot be performed on an <input> field.
When i try to do a .Sendkeys on the iWebElement it will only be able to select values with starting text.
Is there any way to use WebDriver to select the combo box value using the whole text?
Sample DOM is in below format
<input name="icombobox_Text" tabIndex="7" title="Click to select theValue" class="ComboBox_Normal TxtBox_Css" id="icombobox_Text" accessKey="L" onkeydown="return C28.KeyDown();" onkeyup="return C28.KeyUp();" onkeypress="return C28.KeyPress();" onclick="$_('C28','TextClick')" onfocus="$_('C28','Focus')" onblur="$_('C28','Blur')" onselectstart="$_('C28','SelectStart')" onpaste="return false" oncontextmenu="return C28.KeyRightClick()" type="text" maxLength="255" maxSize="10" minSize="5" AUTOCOMPLETE="off"/>
There are 4 items in the combo..How to select a particular value.?
I got the answer.
Concept:
The Combo Control is having Text Box + List (Drop Down image).
So first find the element of the drop down image by clicking it.
Then use “SelectElement” Class to select the value from the list.
Sample Code:
IWebElement iWebelement = driver.FindElement(By.Id("combobox_Text")); //Getting the element of the Text Box
IWebElement iWebelementList = driver.FindElement(By.Id("combobox_List")); //Getting the elements of List/Drop down Box
SelectElement selected = new SelectElement(iWebelementList); //Parsing the list
iWebelement.SendKeys(Keys.ArrowDown); // Clicking the drop down image
selected.SelectByText("January"); // Use select element class to select the value
Use the following below code, to select an Option from Drop Down:
IWebElement iwe = Driver.FindElement(By.XPath("//li[contains(#class,'..item...') and contains(text(),'"+text+"')]"));
Thread.Sleep(500);
Actions action = new Actions(Driver);
Thread.Sleep(500);
action.MoveToElement(iwe).Click().Perform();

Radio Buttons in Selenium C#

I have a form and cannot figure out how to automate the selection of a radio button.
The ID for the one which I need to click is "c100"
html code for the option I need to click:
<input id="cl00" type="radio" name="MYN" value="cl00">
c# code as follows:
driver.FindElement(By.Id("//input[#value='c100']")).Click();
Ive also tried:
IWebElement radio = driver.FindElement(By.Id("c100"));
radio.Click();
I have tried all the different ways including javascript. Can someone plase tell me what I am doing wrong?!
Change:
By.Id("//input[#value='c100']")
To:
By.Xpath("//input[#value='c100']")
Xpaths are useful for finding elements without displayed text or hidden elements.
Use http://www.w3schools.com/XPath/ for future reference.
Hope it helps!

Cant change value in a row

Test should: 1.click on icon 'Edit' row (form fot password changing is apperared); 2. Type a new 'password' ; 3. Click 'OK' button in form.
How its works on Watir + Ruby :
browser.img(:title, "Edit").click #fire_event 'onclick'
browser.text_field(:id,"ID").set 'password' # Set new password
browser.div(:id,"ID").click # Save a password
And password was changed - thats ok.
But when I tried to do the same on Selenium Webdriver + C# password isnt changed.
Code:
driver.FindElement(By.Id(...)).FindElements(By.TagName("img"))[0].Click(); // thats Edit button
driver.FindElement(By.Id(...)).SendKeys("1"); // Typed new password in row
driver.FindElement(By.Id(...)).Click(); // thats 'OK' button.
Guys what I did wrong?
I hope for your help.
If both the textbox and button have the same ID, there's your problem. It's impropper to have more than one instance of an ID per a page. Even if the element type is different, it shouldn't happen. Chrome assumes proper html therefore when you search for an element with an id of 'ID', it grabs the first instance. Here is a work around for that issue:
Open page in Chrome
Right click and "Inspect element" on the element you want to find (one of the elements with duplicate IDs)
Double click on the id that shows up and delete the id='ID' part and hit enter
Right click on that html element again and copy xpath
Change the selector to driver.FindElement(By.XPath("theXpathChromeReturns"));
Also you should check out css & xpath selection for the first element. It makes finding elements much cleaner.
driver.FindElements(By.CssSelector("#myId img")[0].Click();
or
driver.FindElement(By.CssSelector("img[title='edit']");

Categories

Resources