I've been learning automation with C# for some weeks now, though I'm progressing in a slow manner. I'm currently trying to do a certain test using a mock page (automationexercise.com).
The page mocks an E-commerce.
I want to capture the products listed in the main page so I can store their properties and test them.
The original html from the page looks like this:
There is a div, which contains 34 divs with the class class="col-sm-4"
and inside each one of those we have a content like this:
I want to capture the content of the paragraph that appears in the picture that is present in each one of those 34 divs containing the product name.
I wrote this code expecting it to print the name of each product but it returns a selector error:
IList<IWebElement> productos = driver.FindElements(By.CssSelector("div[class=col-sm-4]"));
foreach (IWebElement element in productos)
{
IWebElement asd = element.FindElement(By.XPath("./div[1]/div[1]/div[1]/p[1]"));
TestContext.Progress.WriteLine(asd.Text);
}
I have also tried some more variations, none had any success at all except the following Xpath which returns the content of the paragraph in the firs product 34 times.
//div[@class='productinfo text-center']//p
Can someone please help me understand the correct way to build the selector (be it xpath or css selector) in this case?
With a little tweak in the CssSelector as:
div.productinfo p
all the items can be identified as follows:
To capture the products listed in the main webpage and you can use either of the following locator strategies:
Using CssSelector:
driver.Url = "https://www.allbanglanewspaper.xyz/";
IList<IWebElement> elements = driver.FindElements(By.CssSelector("div.productinfo p"));
foreach (IWebElement ele in elements)
{
Console.WriteLine(ele.Text);
}
Using XPath:
driver.Url = "https://www.allbanglanewspaper.xyz/";
IList<IWebElement> elements = driver.FindElements(By.XPath("//div[contains(@class, 'productinfo')]//p"));
foreach (IWebElement ele in elements)
{
Console.WriteLine(ele.Text);
}
Console Output:
Blue Top
Men Tshirt
Sleeveless Dress
Stylish Dress
Winter Top
...
...
...
Stylish Dress
Winter Top
Summer White Top