oren ben yamin
oren ben yamin

Reputation: 21

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

How do I write this in c#?

Please help me thank you!

Upvotes: 0

Views: 6259

Answers (2)

Dominic Giallombardo
Dominic Giallombardo

Reputation: 955

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

el.Displayed;

Upvotes: 1

philn
philn

Reputation: 323

In your case, the elements have a unique ID. So instead of finding them by class name (which could lead to multiple/inaccurate results), you should use By.Id(...). It is more easy to write by hand than xpath, too.

Let's say your IWebDriver instance is called driver. 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. 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)
{
       ...
}

Upvotes: 1

Related Questions