niazi
niazi

Reputation: 91

how to deal with reused elements in selenium (duplication)

I am unable to locate element that is a button.

1st Button

<div class="col-md-12 col-sm-12 col-xs-6">
<input type="hidden" value="113" name="vendor_id"/>
<input id="vendor_submit" class="btn btn-primary mb10 SaveBtn" type="submit" value="Save & Close" name="submit"/>

I have used this command to locate it

driver.findElement(By.xpath(".//*[@id='vendor_submit']") ).click();

2nd Button

 <div class="col-md-12 col-sm-12 col-xs-6">
<input type="hidden" value="113" name="vendor_id"/>
<input type="hidden" value="" name="vendor_hr_account_id"/>
<input id="vendor_submit" class="btn btn-primary mb10 SaveBtn" type="submit" value="Save" name="submit"/>

Problem

Now as they both are on same page i am unable to locate 2nd button due to duplication factor. Only the difference is type. 1st has value="Save & Close" 2nd has value="Save"

Please help me to locate 2nd button.

Upvotes: 3

Views: 273

Answers (4)

Ruchi Dhole
Ruchi Dhole

Reputation: 95

You can use absolute xpath for both the button, as their positions are different in HTML.

For eg : html/body/div[1]/div[3]/form/div[2]/div[2]/div[1]/div[1]/div[3]

To get this add plugin firebug and firepath in mozilla and get absolute xpath from there by inspect element.

Upvotes: -1

Spandan Thakur
Spandan Thakur

Reputation: 368

You can differentiate by adding the value condition also in your xpath. So basically you can use.//*[@id='vendor_submit' and @value='Save'] instead in your driver.findelement

Upvotes: 1

abinet
abinet

Reputation: 2798

You can use only the value Attribute in xpath:

driver.findElement(By.xpath(".//input[@value='Save']")).click();

Upvotes: 1

Saurabh Gaur
Saurabh Gaur

Reputation: 23825

If there are two elements with the same id, I would suggest you try using cssSelector with its attribute value which would be unique for both and much faster than xpath as below :-

driver.findElement(By.cssSelector("input#vendor_submit[value = 'Save']")).click();

Edited1 :- If you are getting element is not visible exception when you're going to click, you should wait before click using WebDriverWait until element visible and clickable as below :-

WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement submit = wait.until(ExpectedConditions.elementToBeClickable(By.cssSelector("input#vendor_submit[value = 'Save']")));
submit.click();

Edited2 :- If unfortunately above does not work, try to click using JavascriptExecutor as below :-

WebElement el = driver.findElement(By.cssSelector("input#vendor_submit[value = 'Save']"));
((JavascriptExecutor)driver).executeScript("arguments[0].click()",  el);

Upvotes: 1

Related Questions