Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find element by multiple text strings?

I was curious if there was a way to find an element using Selenium and Python 2.7 by multiple "keywords" in any order. Allow me to explain using an example:

keyword1 = raw_input("Keyword: ").lower().title()
keyword2 = raw_input("Keyword: ").lower().title()

    try :
        clickOnProduct = "driver.find_element_by_xpath(\"//*[contains(text(), '" + keyword1 + "')]\").click()"
        exec(clickOnProduct)

This is just a snippet of the code, but how could I incorporate this to look for an element that contains both of these keywords (keyword1, keyword2) in any order? It sounds easy in principle and it probably is, but I am having a hell of a time trying to get this. Any suggestions would be greatly appreciated, thanks.

like image 823
Daniel Iverson Avatar asked Dec 24 '22 06:12

Daniel Iverson


1 Answers

You can dynamically construct the XPath expression using or and contains():

keywords = [keyword1, keyword2, ... ]
conditions = " or ".join(["contains(., '%s')" % keyword for keyword in keywords])
expression = "//*[%s]" % conditions

elm = driver.find_element_by_xpath(expression)

If, for example, keyword1 would be hello and keyword2 would be world, the expression would become:

//*[contains(., 'hello') or contains(., 'world')]

If you want to also handle both lower and upper case, you would need to use translate(), see more in this relevant thread:

  • How to find all elements containing the word "download" using Selenium x-path?
like image 165
alecxe Avatar answered Dec 26 '22 18:12

alecxe