Walter Sommer
Walter Sommer

Reputation: 31

C# FindElement(By...) with two criteria

I am currently trying to automate a checkout process. Now I am stuck, the buttons on the site displaying the sizes are nearly identical, they only differ in value

enter image description here

That's why I wanted to ask if I can differ them by two criteria like class + value.

Code:

using System;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;

namespace selenium1
{
    class MainClass
    {
        public static void Main(string[] args)
        {
            IWebDriver driver = new ChromeDriver();



            driver.Navigate().GoToUrl("https://www.off---white.com/en-de/shopping/off-white-odsy-1000-sneakers-14760681");

            IWebElement element = driver.FindElement(By.());

            element.Click();


        }
    }
}

Thank you in advance for your help!

Upvotes: 2

Views: 103

Answers (2)

undetected Selenium
undetected Selenium

Reputation: 193108

You are right. You can club up the value attribute along with any other attribute e.g. data-test, to construct the locators which would identify the element uniquely within the DOM Tree.

To click() on the element with text as 39 you need to induce WebDriverWait for the desired ElementToBeClickable() and you can use either of the following Locator Strategies:

  • Using CssSelector:

    driver.Navigate().GoToUrl("https://www.off---white.com/en-de/shopping/off-white-odsy-1000-sneakers-14760681");
    new WebDriverWait(driver, TimeSpan.FromSeconds(20)).Until(ExpectedConditions.ElementToBeClickable(By.CssSelector("input[data-test='sizeSelector'][value='23']"))).Click();
    
  • Using XPath:

    driver.Navigate().GoToUrl("https://www.off---white.com/en-de/shopping/off-white-odsy-1000-sneakers-14760681");
    new WebDriverWait(driver, TimeSpan.FromSeconds(20)).Until(ExpectedConditions.ElementToBeClickable(By.XPath("//input[@data-test='sizeSelector' and @value='23']"))).Click();
    

Upvotes: 1

Jack Burke
Jack Burke

Reputation: 101

you could use a CSS selector.

for example: css = element_name[<attribute_name>='<value>']

So in your case it would be:
IWebElement element1 = driver.FindElement(By.CssSelector("input[value='25']") IWebElement element2 = driver.FindElement(By.CssSelector("input[value='27']")

This article should help

Upvotes: 2

Related Questions