Reputation: 23
I'm new to Selenium and Java and I'm trying to select the nth
element by CSS selector.
I want to get desired values from the code below and save them for further use. I have successfully used XPATH that looks like this
//*[@class='search-result__advert' and not(@id)][i]
(i = nth element)
I'm trying to practice getting the values by CSS selector and I came up with this (doesn't work as expected)
.search-result__advert:not([id]):not([data-ad-show]):nth-child(i)
(I've also tried :nth-of-type(i)
)
What I expect for i=3
:
The third element that has no id attribute and no data-ad-show attribute is selected, the value would be Desired value 3.
Instead I get org.openqa.selenium.NoSuchElementException: Unable to locate element: .search-result__advert:not([id]):not([data-ad-show]):nth-child(3)
It works fine for i=1, i=2, i=5.
<ul class="search-result list-unstyled">
<li class="search-result__advert">
<div class="grid grid--rev">
<p>Desired value 1</p>
</div>
</li>
<li class="search-result__advert">
<div class="grid grid--rev">
<p>Desired value 2</p>
</div>
</li>
<li class="search-result__advert" id="signUpWrapper">
<div id="signUpSavedSearch" class="grid">
<p>Advertisment 1</p>
</div>
</li>
<li class="search-result__advert hidden" data-ad-show="ad_list_middle">
<div class="ad" id="ad_list_middle">
<p>Advertisment 2</p>
</div>
</li>
<li class="search-result__advert">
<div class="grid grid--rev">
<p>Desired value 3</p>
</div>
</li>
<li class="search-result__advert">
<div class="grid grid--rev">
<p>etc. etc.</p>
</div>
</li>
</ul>
Upvotes: 2
Views: 933
Reputation: 25542
You can just use the CSS selector
ul.search-result div.grid--rev
This filters out all the ads. Now you can use code to iterate through the list instead of having to rely on iterating using the locator.
Upvotes: 1
Reputation: 33351
I guess the correct css selector will be
.search-result__advert:not(id):not(data-ad-show):nth-last-child(i)
Upvotes: 1
Reputation: 29362
The equivalent css selector would be :
li.search-result__advert:not(id):nth-last-child(2)
For better understanding if you apply nth-child
you can take a look at the below :
:nth-child(n) p:nth-child(2) Selects every <p> element that is the second child of its parent
Read more about CSS_SELECTOR here
Upvotes: 1