通过显示文本查找具有selenium的元素

时间:2023-02-10 19:28:45

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 :

我试图将鼠标悬停在带有selenium的菜单栏中的元素上,但难以找到该元素。元素显示如下:

<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.

这种类型有多个元素,所以我需要通过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?

这也没用。有人能告诉我我做错了什么吗?

1 个解决方案

#1


1  

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 :-

您在By.Xpath中使用了不正确的xpath语法,并且By.LinkText仅适用于具有文本的元素,而By.ClassName看起来没问题,但可能有更多具有该类名称的元素,这就是为什么您无法获得正确的元素,所以你应该尝试使用下面提供的带有文字的xPath: -

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

Or

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

Or

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

Hope it works...:)

希望它有效...... :)

#1


1  

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 :-

您在By.Xpath中使用了不正确的xpath语法,并且By.LinkText仅适用于具有文本的元素,而By.ClassName看起来没问题,但可能有更多具有该类名称的元素,这就是为什么您无法获得正确的元素,所以你应该尝试使用下面提供的带有文字的xPath: -

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

Or

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

Or

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

Hope it works...:)

希望它有效...... :)