Reputation: 3
I can find an element using its XPath, but not using its ID, class, or text. I don't want to use XPath because I know it will break easily.
This is what it looks like:
$browser.div(:xpath => "/html/body/nav/div[1]/div/div[3]/div/div/div[3]/div/div/div[2]/div[1]/div/div[2]/div[2]/div[1]/div[2]/div/div/div").present?
$browser.div(:xpath => "/html/body/nav/div[1]/div/div[3]/div/div/div[3]/div/div/div[2]/div[1]/div/div[2]/div[2]/div[1]/div[2]/div/div/div").click
It returns true and clicks on the element.
Following the path, I find the element, then try use its ID, like:
$browser.div(:id => "PaymentSelector").present?
$browser.div(:id => "PaymentSelector").click
It returns false and times out trying to click. The same happens with text or class.
The element is not inside a frame or iframe.
Why would this happen and how do I fix it?
Upvotes: 0
Views: 1187
Reputation: 46826
As discussed in the comments, the problem is that there are multiple elements with the same id. This can be seen by calling:
$browser.divs(:id => "PaymentSelector").count
#=> 5
Watir returns the first matching element, which in this case, happens to be a hidden element. It is not the one that a user is interested in. You need to craft a more specific locator so that the right element is returned.
One option is to specify the :index
since you now know it is the second one:
$browser.div(:id => "PaymentSelector", :index => 2).click
However, it will likely be more robust to just find the first visible one by using the :visible
locator:
$browser.div(:id => "PaymentSelector", :visible => true).click
Upvotes: 3