ayilmaz ayilmaz - 2 months ago 22
CSS Question

How to iterate sub elements of <ul> in Selenium with C#

I am trying to iterate items of object in Selenium with C#. I am very new to it and trying to find a easy way write a code for my test project.

here is my sample html code, I would like to access those links below...

<ul class="list-menu">
<li>
<ul>
<li><a class="head" href="/seramik-banyo-urunleri">Seramik Banyo &#220;r&#252;nleri</a></li>
<li><a href="/seramik-banyo-urunleri/lavabo">Lavabo</a></li>
<li><a href="/seramik-banyo-urunleri/klozet">Klozet</a></li>


my c# code is like below

IList<IWebElement> results = driver.FindElements(By.XPath("//div[@class='list-menu']/li/lu/li"));


but it doesnt get the links. what can I do to fix this?

Answer

You have a typo in the XPath expression, replace:

//div[@class='list-menu']/li/lu/li

with:

//div[@class='list-menu']/li/ul/li

Or, you can use a more compact CSS selector instead:

driver.FindElements(By.CssSelector(".list-menu > li > ul > li"));

where > means a direct parent-child relationship.

Comments