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.
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With