3

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!

3 Answers 3

2

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

Sign up to request clarification or add additional context in comments.

Comments

0

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]

1 Comment

Thanks for the suggestion, forgot to check back here for any possible solutions but it seems I found my solution prior anyway :)
0

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 :)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.