Angus Timoney
Angus Timoney

Reputation: 45

Python Selenium, how to find an element NOT containing a string

Essentially what I already have is a piece of code which finds all the selenium elements on a page which contain the keyword Matty Matheson Hood (see below):

keyword = 'Matty Matheson Hood'
list = driver.find_elements_by_xpath("//*[contains(text(), '" + keyword + "')]")
print(list)

Now this works fine, however, it returns 4 elements and I'm trying to narrow it down to 1 by getting rid of those which contain the keyword Tie Dye

Put simply I was wondering whether I could use something similar to what I have above, but instead use not contains, and is it possible to merge both contains and not contains into 1 search?

So find all elements (should only be 1) which contain Matty Matheson Hood but don't contain Tie Dye.

Any help is appreciated!

Upvotes: 3

Views: 2143

Answers (3)

supputuri
supputuri

Reputation: 14145

Here is the pure xpath that will return only the elements which contains Matty Matheson Hood and not contains Tie Dye.

//*[contains(text(), 'Matty Matheson Hood')][not(contains(text(),'Tie Dye'))]

Screenshot: enter image description here

Upvotes: 2

Angus Timoney
Angus Timoney

Reputation: 45

I managed to solve my problem via a multi-list workaround:

    positive_list = driver.find_elements_by_xpath("//*[contains(text(), '" + positive_keyword + "')]")
    negative_list = driver.find_elements_by_xpath("//*[contains(text(), '" + negative_keyword + "')]")

    result_list = [item for item in positive_list if item not in negative_list]

It might not be the most efficient system but it works for my purpose. Feel free to add more effective methods if you find any :)

Upvotes: 0

David Silveiro
David Silveiro

Reputation: 1602

We could use list comprehension and remove all our desired items from the list, which we no longer need.

An option could be the following:

some_list = driver.find_elements_by_xpath("//*[contains(text(), '" + keyword + "')]")

matching = [s for s in some_list if "Tie Dye" in s]

List comprehensions are used for creating new lists from other iterables.

As list comprehensions returns lists, they consist of brackets containing the expression, which is executed for each element along with the for loop to iterate over each element.

This is the basic syntax:

new_list = [expression for_loop_one_or_more conditions]

Upvotes: 0

Related Questions