Search code examples
javahtmlseleniumautomation

How to use selenium methods to choose web elements


I am very new to selenium and I just want to know how I can select a radio button with the following html:

HTML Code:

<div ng-class={'selected':profile.info.carUnder20k==false||profile.info.carUnder20k=='false'}" ng-click="onChoice($event, 'carUnder20k', 'false');" data-field="carUnder20k" class="choice         selected" style="">N</div>

Sorry Multiline doesn't work...

I want to select this element but I don't want to use it's XPATH. Is there a way in selenium where I could choose an element by data-(anything) attribute? In this case it is data-field="carUnder20K". Or something that would be unique to this element?

Java Code: (This is what I'm doing now but using a custom framework, which works but is very unreadable.)

WebDriver driver = new FireFoxDriver();
driver.findElement(By.xpath("/html/body/div[2]/div/div/div[1]/form/div/section[1]/div[6]/div[2]/select/option[@value='0']")).click();

I've also tried:

driver.ElementByDivText("N").click();

But there is another element almost identical to this one, only the data-field here is different. So WebDriver just reclicks this other element I've already clicked, not the new one I'd like to select.

Any selenium wizards out there?

EDIT:

Sorry I forgot the fact that each button has it's own HTML

Yes Button/Radio:

<div ng-class="{'selected':profile.info.carUnder20k==true||profile.info.carUnder20k=='true'}" ng-click="onChoice($event, 'carUnder20k', 'true');" data-field="carUnder20k" class="choice" style="">Y</div>

No Button/Radio:

<div ng-class="{'selected':profile.info.carUnder20k==false||profile.info.carUnder20k=='false'}" ng-click="onChoice($event, 'carUnder20k', 'false');" data-field="carUnder20k" class="choice selected" style="">N</div>

Solution

  • You can use CSS for this:

    driver.findElement(By.cssSelector("[data-field='carUnder20k']")).click();
    

    Edit: For what you are describing in your comment, it may be that an xpath approach would work better:

    driver.findElement(By.xpath("//div[@data-field='carUnder20k' and text()='N']")).click();