What xpath can I use if the tag name in the code starts with li
or span
and they are child or parent. The trip id and the name locator didn't execute.
What xpath can I use if the tag name in the code starts with li
or span
and they are child or parent. The trip id and the name locator didn't execute.
Using xpath to locate an element works regardless of the parents of the element. It doesn't matter if the parent is an li or a span, as long as your identifier is unique. So if you are using a CSS ID it will work.
Now that CSS ID needs to be unique or if you are using elements and classes, their combined selection needs to be unique. This can be a challenge if multiple similar elements exist and/or similar elements exist at other elements within the DOM for the parent element. The answer is to learn how to identify elements for automation and to do that I recommend you read up a couple of books and blogs.
http://selenium-python.readthedocs.io/locating-elements.html is a great reference that is not only good for pythonists
https://sensequalityassurance.wordpress.com/2015/05/05/webdriver-commands-and-notes/ may also help
http://www.seleniumeasy.com/selenium-tutorials/css-selectors-tutorial-for-selenium-with-examples has some great examples
Two examples that may help:
First:
Selecting child elements
//form/child::input[@type='password']
This would select all child-element nodes named input which @type-attribute-values are equal to 'password'. The child:: axis prefix may be omitted, because it is the default behaviour, so this becomes
//form/input[@type='password']
Second:
Selecting an immediate child vs any child under that element:
Immediate child ('/
'): span/form
Any level deep child ('//
') span//form
Many elements would work for both approaches. The //
approach allows for the page to be rearranged and thus may be more flexible. The /
approach may be helpful to more specificially identify an element when more than 1 exist in the tree below the parent element
Instead of using XPath, try the below code, it will be useful in dynamic variables also.
String searchText = "your element's text";
WebElement dropdown = driver(or your parent locator of ul).findElement(By.tagName("ul"));
List<WebElement> options = dropdown.findElements(By.tagName("li"));
System.out.println(options);
for (WebElement option : options)
{
if (option.getText().equals(searchText))
{
option.click(); // click the desired option
}
}