How to find an item across multiple lines of text?

I was curious if there is a way to find an element using Selenium and Python 2.7 with a few “keywords” in any order. Let me 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 piece of code, but how can I include it in the search for an element that contains both of these keywords ( keyword1, keyword2 ) in any order? It sounds simple in principle, and probably it does, but I have time trying to get it. Any suggestions would be greatly appreciated, thanks.

+4
source share
1 answer

XPath or contains():

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

elm = driver.find_element_by_xpath(expression)

, , keyword1 hello, keyword2 world, expression :

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

, , translate(), . :

+6

All Articles