1

The FindElement() method doesn't seem to work with an XPath locator, if called on an existing WebElement.

My code is this:

htmlDiv = _driver.FindElement(By.XPath("//h2[text()='" + onvNaam + "']/../.."));
htmlControl = htmlDiv.FindElement(By.XPath("//label[text()='Naam']/following-sibling::div[1]//select"));

The result of this code is that htmlControl contains the first matching element in the page, not the matching element in htmlDiv.

For other controls (with other By types) this seems to work.

Is the Xpath double slash superceding the scope of htmlDiv?

asked Oct 17, 2014 at 11:00
1

3 Answers 3

2

Ok, this isn't a bug. The XPath, when searching in the context of an element, must start with a dot. So this works:

htmlControl = htmlDiv.FindElement(By.XPath(".//label[text()='Naam']/following-sibling::div[1]//select"));
answered Oct 20, 2014 at 5:46
2

Do two simple steps:

First initialise webdriver element then try to find element using xpath, as explained below

WebDriver driver=new FirefoxDriver();
driver.find element(By.xpath("enter your xpath")).click();
Kate Paulk
31.5k8 gold badges56 silver badges109 bronze badges
answered Oct 20, 2014 at 6:45
1
  • Xpath is the best way to find an element followed by id, cssselector and name... Commented Oct 29, 2014 at 12:27
0

According to Selenium best practices, XPath is locator of last preference.

Preferred selector order : id> name> css> xpath

Ask your web designers to add IDs or names to elements you need to interact with. Take them to the lunch and talk how IDs make your life easier. Bribe them is you have to.

answered Oct 17, 2014 at 12:46
2
  • Fully agree, but that doesn't mean the provided functionalities should have bugs. :) Also, I'm running into vaguely comparable issues with the CssSelector. Commented Oct 17, 2014 at 13:31
  • 1
    Go and fix it - it is open source. Easy. Or switch to some proprietary tools which are known to have no bugs, ever. Commented Oct 17, 2014 at 16:56

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.