I had been having a problem trying to select an item in a dropdown. I have checked resources online but I still couldn't get it working. My HTML is this:
<div id="dropdownID">
<ul class="ulList">
<li class="liItem"> Number 1 </li>
<li class="liItem"> Number 2 </li>
</ul>
</div>
while my selenium C# is:
var drop = Driver.FindElement(By.Id("dropdownId")).FindElement(By.Xpath("//ul/li[(@class='liItem') and contains(text(),'{0}')]")).click();
drop.SendKeys(value);
Where {value} is a string that I would like to input on sendkeys. The error would be:
no such element: Unable to locate element: {"method":"xpath","selector":"//ul/li[(@class='liItem') and contains(text(),'{0}')]"}
2 Answers 2
Your problem is with the selector indeed.
Issue 1
When using XPath in the context of another element (as you are doing), always start the XPath with a dot (which represent the element you are starting from). For example, .//ul/li
Issue 2
You haven't formatted your variable text into your XPath, it says {0}
.
So first do a string.Format
on your XPath, then pass that as the locator value.
var xpath = string.Format(".//li[contains(text(),'{0}')]", "Number 1");
var drop = Driver.FindElement(By.Id("dropdownId")).FindElement(By.Xpath(xpath)).click();
drop.SendKeys(value);
-
Ok, sorry. I have added a thread.sleep before the var xpath. thanks so much @FDM! I have added .//ul//li too though to avoid the invalid xpath expressionMarj– Marj2017年07月05日 19:47:36 +00:00Commented Jul 5, 2017 at 19:47
Note: in this answer, DivElement
represents Driver.FindElement(By.Id("dropdownID"))
.
You can locate the first unordered list item by XPath with the following:
a. DivElement.FindElement(By.XPath(".//li"))
b. DivElement.FindElements(By.XPath(".//li")).ElementAt(0)
Moreover, you can find this item by:
1. Class Name
a. DivElement.FindElement(By.ClassName("liItem"))
b. DivElement.FindElements(By.ClassName("liItem")).ElementAt(0)
2. Tag Name
a. DivElement.FindElement(By.TagName("li"))
b. DivElement.FindElements(By.TagName("li")).ElementAt(0)
3. CSS Selector
a. DivElement.FindElement(By.CssSelector(".liItem"))
b. DivElement.FindElements(By.CssSelector(".liItem")).ElementAt(0)