Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find element with selenium by display text

Tags:

html

c#

selenium

I am trying to hover over an element in a menu bar with selenium, but having difficulty locating the element. The element is displayed below :

<DIV onmouseover="function(blah blah);" class=mainItem>TextToFind</DIV>

There are multiple elements of this type so I need to find this element by TextToFind.

I've tried :

driver.FindElement(By.XPath("TextToFind"))

and

driver.FindElement(By.LinkText("TextToFind")) 

which both didn't work. I even tried:

driver.FindElement(By.ClassName("mainItem")) 

which also did not work. Can someone tell me what I am doing incorrectly?

like image 971
Pseudo Sudo Avatar asked Jul 29 '16 14:07

Pseudo Sudo


People also ask

Can XPath locate element using text?

text(): A built-in method in Selenium WebDriver that is used with XPath locator to locate an element based on its exact text value.

How do I find an element that contains specific text in Selenium Webdriver Python?

Use driver. find_elements_by_xpath and matches regex matching function for the case insensitive search of the element by its text.

How can you find if an element is displayed on the screen in Selenium?

We can verify whether an element is present or visible in a page with Selenium webdriver. To check the presence of an element, we can use the method – findElements. The method findElements returns a list of matching elements. Then, we have to use the method size to get the number of items in the list.

How does Selenium check text is visible?

isDisplayed() The isDisplayed method in Selenium verifies if a certain element is present and displayed. If the element is displayed, then the value returned is true. If not, then the value returned is false.


2 Answers

You are using incorrect syntax of xpath in By.Xpath and By.LinkText works only on a element with text and By.ClassName looks ok but may be there are more elements with that class name that's why you couldn't get right element, So you should try use below provided xPath with text :-

driver.FindElement(By.XPath("//div[text() = 'TextToFind']"));

Or

driver.FindElement(By.XPath("//div[. = 'TextToFind']"));

Or

driver.FindElement(By.XPath("//*[contains(., 'TextToFind')]"));

Hope it works...:)

like image 91
Saurabh Gaur Avatar answered Sep 23 '22 03:09

Saurabh Gaur


Better ignoring the whitespaces around the text with this:

var elm = driver.FindElement(By.XPath("//a[normalize-space() = 'TextToFind']"));

This searches text within an [a] element, you can replace it with any element you are interested in (div, span etc.).

like image 33
ozanmut Avatar answered Sep 22 '22 03:09

ozanmut