I'm new to selenium and HTML. I want to perform click operation for the elements "Users" and "Admins" as one after another. Below mentioned is the HTML code, unfortunately I can't modify it.
<ul id="nav">
<li class="">
<a class="mainmenu" title="List of Users" menuid="nav_0">
<span class="title">Users</span>
<span class="arrow"/>
</a>
<ul class="sub-menu">
<li>
<a class="mainmenu" title="List of Admins" menuid="nav_0-sub_0">Admins</a>
</li>
</ul>
</li>
<li class="">
<a class="mainmenu" title="List of Contents" menuid="nav_1">
<span class="title">Contents</span>
</a>
</li>
<li class="">
<a class="mainmenu" title="Repos" menuid="nav_2">
<span class="title">Repository</span>
</a>
</li>
I have used XPath like this:
.//*[@id='nav']/li[1]/a[contains(@title, 'List of Users']
Any other ways to get the element like matching the text value? Because the list elements order is dynamic, so the current position of the element "Users"(li[1]
) might get change later.
4 Answers 4
As per given description, it seems that list of users will be maintained in HTML's List Item having common title=List of Users. So you can use something like below code to click on dynamic list items(here, users).
List<WebElement> Userlist = driver.findElements(By.cssSelector("a[title='List of Users']");
for(WebElement ulist : Userlist)
{
//Do your action, e.g. click() with each user name.
}
-
I find it hilarious that the accepted answer shows how to do it with a CSS locator when the OP explicitly asked for an XPath solution and there are valid XPath answers...Ardesco– Ardesco2019年06月03日 09:17:02 +00:00Commented Jun 3, 2019 at 9:17
You can try creating xpath with text()
like these:
//span[contains(text(),'Users')]
//span[contains(text(),'Contents')]
-
It failed to pick element by using this.jass– jass2015年09月23日 07:08:35 +00:00Commented Sep 23, 2015 at 7:08
-
2Pankaj Kumar Katiyar/demouser123 is missing the closing bracket
]
.//span[contains(text(),'Users')]
//*[contains(text(),'Users')]
//span[text()='Users']
//*[text()='Users']
//a[contains(text(),'Admins')]
//*[contains(text(),'Admins')]
//a[text()='Admins']
//*[text()='Admins']
any of these should workRoskoe– Roskoe2018年09月17日 19:48:18 +00:00Commented Sep 17, 2018 at 19:48
To avoid the li[1]
, just use this XPath. It will still work, even if one of the li
elements swap their locations in the html file.
//*[@id='nav']/li/a[contains(@title,'List of Users')]
If you only have one <a>
element on the page, you could avoid the li
part
//a[contains(@title,'List of Users')]
//*[@id='nav']/li[1]/a[contains(@title, 'List of Users']
You missed )
at the last ]
, it should be like below:
//*[@id='nav']/li[1]/a[contains(@title, 'List of Users')]