There is a page on which there are 4 identical elements, but with different text Request

browser.find_elements_by_xpath("//*[@class='MyClassName']")

returns me all 4 items at once. Elements differ only in text. I know part of this text, because the other part contains time and ID. I can get them through comparison with the text, but it looks terrible, long and difficult.

[x for x in browser.find_elements_by_xpath("//*[@class='MyClassName']") if my_text in x.text][0].click()

Is it possible to somehow get an element by class name and through contains text? I tried

 browser.find_elements_by_xpath( "//*[@class='MyClassName' and [contains(text(),'{}')]]".format(my_text)) 

But selenium swears SyntaxError: Failed to execute 'evaluate' on 'Document': The string "//*[@class='MyClassName' and [contains(text(),'Custom')]]" is not a valid XPath expression. Question: how to make the correct xpath?

    2 answers 2

     browser.find_elements_by_xpath( "//*[@class='MyClassName' and text()[contains(.,'{}')]]".format(my_text)) 

      I would suggest a cycle on elements. But if you don’t feel like it at all, SelectorGadget can help. This is a plugin for Chrome. Helps to access a specific element through both the CSS selector and xpath.

      • Written via Selenium - Alex78191
      • The selector can be generated through the developer tools. But in the text they are not created automatically. - Alex78191