简体   繁体   English

如何在span标签Selenium中使用Id或Xpath查找元素

[英]How to find element using Id or Xpath inside a span tag Selenium

I want to select this particular text "Password field is required." 我要选择此特殊文本“需要密码字段”。 , which is apparently inside the <span> tag. ,显然位于<span>标记内。

<span id="password" class>
::before
"Password field is required."
</span>

I tried to find the element using the Id but unfortunately it doesn't seem to work. 我尝试使用Id查找元素,但不幸的是,它似乎不起作用。 My code is like this : 我的代码是这样的:

var emptyPassword = WebBrowser.Current.FindElement(By.Id("password"));
Assert.AreEqual("Password field is required.", emptyPassword);

I also tried using Xpath but still no luck. 我也尝试使用Xpath但仍然没有运气。 The Xpath look like this: Xpath看起来像这样:

//*[@id="password"]

Can somebody explain to me why i can't locate the element using Id or xpath? 有人可以向我解释为什么我无法使用Id或xpath定位元素吗? thanks :) 谢谢 :)

With the HTML you show and the code you show Selenium should be able to find your element. 使用显示的HTML和显示的代码Selenium应该能够找到您的元素。 However, you are not asserting that its text is the value you want so perform the assertion like this: 但是,您并不是在断言其文本是您想要的值,因此请执行如下断言:

Assert.AreEqual("Password field is required.", emptyPassword.Text);

Note the added .Text at the end, which gets the text of the element. 请注意最后添加的.Text ,它获取元素的文本。 What FindElement returns is a WebElement object, not a string. FindElement返回的是WebElement对象,而不是字符串。

Do a text based search. 进行基于文本的搜索。

.//*[.='Password field is required.']

by . 由。 you are pointing to parent element here. 您在这里指向父元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM