简体   繁体   English

使用XPath的C#硒查找元素

[英]c# selenium finding element using xpath

I am trying to find an element which is a div inside a div... here is example of the code: 我试图找到一个元素,它是一个div内的一个div ...这是代码示例:

<div class="col-md-4">
    <div style="display: none;" id="multiplier-win" class="label label-success multiplier">2X</div>
    <div style="display: block;" id="multiplier-lose" class="label label-danger multiplier">0X</div>
    <div style="display: none;" id="multiplier-tie" class="label label-warning multiplier">1X</div>
</div>

I want to find the class="label label-success multiplier" and check if her style="display:none" . 我想找到class="label label-success multiplier"并检查她的style="display:none"

How do I write this in c#? 如何用C#编写?

Please help me thank you! 请帮我谢谢!

In your case, the elements have a unique ID. 在您的情况下,元素具有唯一的ID。 So instead of finding them by class name (which could lead to multiple/inaccurate results), you should use By.Id(...) . 因此,应该使用By.Id(...)而不是通过类名查找它们(这可能导致多个/不正确的结果By.Id(...) It is more easy to write by hand than xpath, too. 与xpath相比,手工编写也更容易。

Let's say your IWebDriver instance is called driver. 假设您的IWebDriver实例称为驱动程序。 The code looks like this: 代码如下:

IWebElement element = driver.FindElement(By.Id("multiplier-win"));
String style = element.GetAttribute("style");
...

I don't want to offend you, but you should probably use google before you post here. 我不想冒犯您,但在发布此信息之前,您可能应该使用google。 This is very basic code you will find in multiple tutorials about selenium. 这是非常基本的代码,您可以在有关硒的多个教程中找到。

Edit: In case you are looking for multiple elements of a class: 编辑:如果您正在寻找一个类的多个元素:

ReadOnlyCollection<IWebElement> elements = driver.FindElements(By.ClassName("..."));

foreach (IWebElement el in elements)
{
       ...
}

To Find the element: 查找元素:

IWebElement element = driver.FindElement(By.XPath("//div[@class='label label-success multiplier']"));

To check if an element is displayed, this returns a bool (true if displayed, false if not displayed). 要检查是否显示元素,这将返回bool(如果显示则为true,如果未显示则为false)。 If you go with philn's element list code, you can throw this line into his foreach statement and it will tell you which ones are displayed. 如果使用philn的元素列表代码,可以将此行放入他的foreach语句中,它将告诉您要显示的内容。

el.Displayed;

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

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