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?

FDM
  • 5,894
  • 1
  • 16
  • 34
  • Maybe its a defect in Selenium, since I think it should work like you want it to work. You could try to build a small HTML page to verify your findings and see if there is a difference between using // or not. Afterwards maybe ask on the Selenuim newsgroups: https://groups.google.com/forum/#!forum/selenium-users or post an issue to the bugtracker: https://code.google.com/p/selenium/issues/list – Niels van Reijmersdal Oct 17 '14 at 11:11

3 Answers3

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"));
FDM
  • 5,894
  • 1
  • 16
  • 34
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,513
  • 8
  • 54
  • 108
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.

  • Fully agree, but that doesn't mean the provided functionalities should have bugs. :) Also, I'm running into vaguely comparable issues with the CssSelector. – FDM Oct 17 '14 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. – Peter M. - stands for Monica Oct 17 '14 at 16:56