-1

I use find_elements_by_xpath to know if keywords exists

driver.find_elements_by_xpath('//*[contains(text(), "' + str(key) + '")]') 

when keyword = 0.5 HR which returns 0.5 HR (correctly)

when keyword = 5 HR which still returns both 5 HR and 0.5 HR (wrong, 0.5 HR is not 5 HR)

Is it possible to avoid?

undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
codenew
  • 1
  • 1

2 Answers2

0

I'm imagine you have following code snippet:

<div>
    <div>0.5 HR</div>
    <div>5 HR</div>
</div>

If you query with contains function with value 5 HR like this:

//*[contains(text(), "5 HR")]

Sure it will return 2, because there are indeed 2 elements that contain 5 HR text.

May you want query with exact value, so you can't use contains function.

Use equal = :

driver.find_elements_by_xpath('//*[text()="' + str(key) + '"]')
frianH
  • 7,295
  • 6
  • 20
  • 45
0

To start with, using contains(text(), "sometext") may make the expression a bit flaky. I would have used either text() or contains(string, string)


text()

text() considers/selects all text node children of the context node


contains()

contains() function returns true if the first argument string contains the second argument string, and otherwise returns false.


An example

Consider the example below:

  • HTML:

    <ul>
        <li>0.5 HR</li>
        <li>5 HR</li>
    </ul>
    
  • To select only the node with text as 0.5 HR you need to use:

    //key = 0.5 HR
    driver.find_elements_by_xpath("//li[text()='" + str(key) + "']") 
    
  • To select only the node with text as 5 HR you need to use:

    //key = 5 HR
    driver.find_elements_by_xpath("//li[text()='" + str(key) + "']") 
    
  • To select both the nodes with text as 0.5 HR and 5 HR you need to use:

    //key = 5 HR
    driver.find_elements_by_xpath("//li[contains(., '" + str(key) + "')]")
    

Reference

You can find a detailed discussion in:

undetected Selenium
  • 183,867
  • 41
  • 278
  • 352