Home > Mobile >  know if the text contained in the tag is equal or not to a specific text
know if the text contained in the tag is equal or not to a specific text

Time:02-11

Here is my probleme: I have two tags.

<div class='twoLink'
<a class='link' <div> microsoft word </div></a>
<a class='link' <div> word </div></a>
</div>

My goal is to click on the tag containing only the word "word" and not "microsoft word".

so I did this :

element = 'word'
linkWord = WebDriverWait(driver, timeout=5).until(EC.element_to_be_clickable(
         (By.XPATH,"//a[contains(@class, 'link')]/div[contains(text(), '"  element  "')]")))
         driver.execute_script("arguments[0].click();", linkWord )

But this method makes me click on the tag containing "word" and not equal to "word", so the tag I click is the first one and not the second one as I would have liked.

I would have to find a method to check an equality but I didn't find one.

What can I do about it please ?

CodePudding user response:

//a[@class='link']/div[text()='word'] 

which is simply

f"//a[@class='link']/div[text()='{element}']"

Remove contains and then just use text() to compare what the div tag value is.

CodePudding user response:

Here is a way you can assert if the word is present. I noticed that you are using contains because there is a space preceding the word word in element DOM, but contains is fetching the microsoft word since it contains word in in it. So, the below approach works. I have added asserts in a conditional statement to be clear, but you can actually reduce it to one line assert x == 'word', "not the right word

x = driver.find_element(By.XPATH, "//div[@class='twoLink']//following-sibling::a").text
print(x)
if x == 'word':
    print("True")
    assert True
else:
    print("False")
    assert False

Output:

word
True

Process finished with exit code 0

This also works:

//a[@class='link' and text()=' word ']

One more strategy would be to use normalize. Please research on that if you would like to use it. Here is the normalized-space locator. This would find you your element:

//a[normalize-space(text()='word')]
  • Related