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?
text(): A built-in method in Selenium WebDriver that is used with XPath locator to locate an element based on its exact text value.
Use driver. find_elements_by_xpath and matches regex matching function for the case insensitive search of the element by its text.
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.
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.
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...:)
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.).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With