问题
I am using Selenium Protractor and want to select all elements from the following list except one that contains text "Cat" and then perform some operations on the remaining ones.
<div class="mainDiv">
<div class="childDiv">Dog</div>
<div class="childDiv">Goat</div>
<div class="childDiv">Bird</div>
<div class="childDiv">Cat</div>
<div class="childDiv">Zebra</div>
</div>
Is there a selector by cssContainingText (or some other) in which I can give a condition to select all elements except the one containing text "Cat"?
回答1:
You can create a List selecting all the elements except one that contains text Cat using the following Locator Strategy:
xpath:
//div[@class='mainDiv']//div[@class='childDiv'][not(contains(.,'Cat'))]
When using Selenium and css-selectors:
The :contains pseudo-class isn't in the CSS Spec and is not supported by either Firefox or Chrome (even outside WebDriver). You can find a detailed discussion in selenium.common.exceptions.InvalidSelectorException with “span:contains('string')”
However, if the elements always appears within the DOM Tree in a specific order, e.g. Cat always at the forth child, you can also use:
cssSelector:
div.mainDiv div.childDiv:not(:nth-child(4))
Reference
You can find a couple of relevant discussions in:
- While fetching all links,Ignore logout link from the loop and continue navigation in selenium java
- How to write a CSS Selector selecting elements NOT having a certain attribute?
来源:https://stackoverflow.com/questions/62043616/protractor-conditional-selector