jessica
jessica

Reputation: 1517

How to click an item from a list in Selenium WebDriver using C#?

Hi I need to verify if the item I'm going to click has a dollar sign and is not out of stock. So I have used this method.This works fine if the first item on the list satisfies both the condition but in case if the first item doesn't have a dollar sign it does not go to the second item and click it, instead it fails. As I'm new to programming I don't know if I have made any mistake in the code. How can I correct this ? Thanks.

Code:

        ReadOnlyCollection<IWebElement> listOfItems = driver.FindElements(By.CssSelector("ul[class='shelf-list tap-list search']>li"));
            foreach (IWebElement item in listOfItems)
            {
                //To check if item is not sold out get the class attribute of item and check if empty
                string className = item.GetAttribute("class");
                Console.WriteLine("Classname:" + " " + className);
                if (className.Equals(""))
                {
                    //Item is available and now get text and check if it has $ sign
                    IWebElement itemWithDollarSign = driver.FindElement(By.CssSelector("div[class='item-preview-text']>div[class='price']"));
                    string ItemToChoose = itemWithDollarSign.Text;
                    Console.WriteLine("Text:" + " " + ItemToChoose);
                    if (ItemToChoose.Contains("$"))
                    {
                        //Choose the item that satifies both conditions
                        itemWithDollarSign.Click();
                        break;
                    }
                }
            }

Case 1 output: if item satisfies both condition

Classname:
text: $189

// shows classname is empty and it entered the loop.

case 2 output: if first item doesnot have $

Classname:
text: Prices varies
Classname:
text: Prices varies
Classname:
text: Prices varies...

keeps repeating the same for 30 items on page instead of going to second one.

Upvotes: 1

Views: 2261

Answers (1)

DonBoitnott
DonBoitnott

Reputation: 11035

The inner FindElement appears to want to get itemWithDollarSign related to the looping item, but it appears to actually be static.

This library isn't my bread and butter, but could this be it:

IWebElement itemWithDollarSign = item.FindElement(By.CssSelector("div[class='item-preview-text']>div[class='price']"));

Upvotes: 3

Related Questions