jetrldz
jetrldz

Reputation: 35

Using contains() function with selenium on Python

I'm trying to use contains function on selenium and trying to do a certain action if that specific text exists and click on it.

How to use contains function with driver.find.element(). So far I tried:

if driver.find_element(By.LINK_TEXT, contains("Hello World")) == True:
    driver.find_element(By.LINK_TEXT, "Hello World").click() 

and some variations of it.

Element:

<a href="/xyz" target="_blank" class="btn btn-primary inline-flex items-center px-3 py-2 border border-transparent text-sm leading-4 font-medium rounded-md shadow-sm text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500">"Hello World"</a>

Upvotes: 1

Views: 2867

Answers (4)

jetrldz
jetrldz

Reputation: 35

Found that rather than using contains() function I simply used

def xyz():
    try:
        driver.find_element(By.CSS_SELECTOR, "button[class='h-10']")
    except NoSuchElementException:
        return False
    return True

to check if that specific class, button, etc. exists and creating while, if functions to make decisions.

For example:

i = 0
while i<10:
    xyz()
    if xyz() == True:
        driver.get("https://www.google.com/")
    else:
        abc()

Upvotes: 0

Prophet
Prophet

Reputation: 33351

First of all you should use driver.find_elements method, not driver.find_element because in case of no such element found driver.find_element will throw exception, it will not return a Boolean False.
While driver.find_elements will return a list of matching web elements. In case there were matches found it will return a non-empty list, and it will be interpreted by Python as Boolean True. Otherwise, if no matches found, it will return an empty string, and it will be interpreted by Python as Boolean False.
As mentioned by AbiSaran you can use driver.find_element(By.XPATH, and in case the string contains ' you can use a slash as following"

if driver.find_elements(By.XPATH, "//a[contains(.,'fellow\'s world')]"):
    driver.find_element(By.XPATH, "//a[contains(.,'fellow\'s world')]").click()

Or

elements = driver.find_elements(By.XPATH, "//a[contains(.,'fellow\'s world')]")
if elements:
    elements[0].click()

Upvotes: 0

Michael Mintz
Michael Mintz

Reputation: 15381

There's the By.PARTIAL_LINK_TEXT selector option that can do substrings of link text.

Upvotes: 0

AbiSaran
AbiSaran

Reputation: 2678

You can use contains():

driver.find_element(By.XPATH,".//*[contains(.,'Hello World')]")

or

driver.find_element(By.XPATH,".//*[contains(text(),'Hello World')]")

or

driver.find_element(By.XPATH,".//*[contains(@id,'Hello World')]")

Syntax:

//tagName[contains(@attribute_name,'attribute_value')] 

or

//*[contains(@attribute_name,'attribute_value')]

or

//*[contains(text(),'value')]

Upvotes: 2

Related Questions