Reputation: 1452
We've got some poorly written radio buttons on a legacy page as follows:
<input id="button1" name="button" value="32" onchange="assignProduct(this.value);" type="radio"></input>
RADIO TEXT 1
<input id="button2" name="button" value="33" onchange="assignProduct(this.value);" type="radio"></input>
RADIO TEXT 2
for information, this displays the same as would:
<input id="button" name="button" value="32" onchange="assignProduct(this.value);" type="radio">RADIO TEXT 1</input>
<input id="button" name="button" value="33" onchange="assignProduct(this.value);" type="radio">RADIO TEXT 2</input>
The latter code is more correct and allows selection of input button by text "RADIO TEXT 2" by:
driver.findElement(By.xpath("(//input[contains(@text, 'RADIO TEXT 2')])")).click();
What code can I use to find the radio button in the first code sample, which is what I actually have to deal with?
The text is no longer contained within the element so .xpath() doesn't match it.
I need to find the text, then click the input immediately prior? Can I do this without consuming and traversing the entire page?
Upvotes: 1
Views: 9608
Reputation: 2019
Use XPath axes. In this particular case following-sibling
. I've designed a locator to demonstrate it on this page. Look at the @bansalshah's answer. Lets select <p>
where the following text contains for eg
. It works, Ive checked this :)
.//*[@id='answer-25883774']//div[@class='post-text']/p[./following-sibling::*[contains(., 'for eg')]]
So, in your case, to select the input for RADIO TEXT 2 this should be something like
.//input[@type='radio'][./following-sibling::*[contains(., 'RADIO TEXT 2')]]
Upvotes: 1
Reputation: 1515
For the first example, you can access buttons by there ID
:
driver.findElement(By.id("button1")).click(); //first button
and
driver.findElement(By.id("button2")).click(); //second button
If the Id is not enough, you can, using xpath
, access to them via id
and value
:
driver.findElement(By.xpath("//input[@id='button1'][@value='32']")).click(); //first button
and
driver.findElement(By.xpath("//input[@id='button2'][@value='33']")).click(); //first button
Upvotes: 1
Reputation: 29
From the code which i can see you can map the values with text
for eg value=32 for radio text 1 and get the value from the xpath
if value =32 then select the radio button
Hope this helps
Upvotes: 0