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?
-
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: groups.google.com/forum/#!forum/selenium-users or post an issue to the bugtracker: code.google.com/p/selenium/issues/listNiels van Reijmersdal– Niels van Reijmersdal2014年10月17日 11:11:58 +00:00Commented Oct 17, 2014 at 11:11
3 Answers 3
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"));
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();
-
Xpath is the best way to find an element followed by id, cssselector and name...IAmMilinPatel– IAmMilinPatel2014年10月29日 12:27:32 +00:00Commented Oct 29, 2014 at 12:27
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– FDM2014年10月17日 13:31:13 +00:00Commented Oct 17, 2014 at 13:31
-
1Go 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– Peter M. - stands for Monica2014年10月17日 16:56:22 +00:00Commented Oct 17, 2014 at 16:56
Explore related questions
See similar questions with these tags.