4
votes

Im trying to automaticly test all the links on a site. But the problem is that my foreach loop stops after the first click.

When I Console.log the attribute it writes out all the links but wont do the same when its time to Click around :)

This logs out all the links.

 [FindsBy(How = How.TagName, Using = "a")]
 public IWebElement hrefClick { get; set; }

    public void TestT2Links()
    {
        foreach (IWebElement item in PropertiesCollection.driver.FindElements(By.TagName("a")))
        {
            Console.WriteLine(item.GetAttribute("href"));
            
        }
    }

But when im trying to Click() function it only clicks the first link.

 [FindsBy(How = How.TagName, Using = "a")]
 public IWebElement hrefClick { get; set; }

    public void TestT2Links()
    {
        foreach (IWebElement item in PropertiesCollection.driver.FindElements(By.TagName("a")))
        {
            hrefClick.Click();
              
            Console.WriteLine(item.GetAttribute("href"));
        }
    }

I also tried the back method to back navigate after every click but also useless and wrong :(

PropertiesCollection.driver.Navigate().Back();

Any tips?

3

3 Answers

5
votes

You need to find ALL links. The [FindsBy] you are using returns a link not the list. First find a collection

[FindsBy(How = How.TagName, Using = "a")]
public IList<IWebElement> LinkElements { get; set; }

Edit

Just heads up, simply clicking through a list of WebElements will possibly return StaleElement reference exception due to DOM refresh. Use for loop and find the element runtime.

[FindsBy(How = How.TagName, Using = "a")]
public static IList<IWebElement> LinkElements { get; set; }


private void LoopLink()
{
    int count = LinkElements.Count;

    for (int i = 0; i < count; i++)
    {
        Driver.FindElements(By.TagName("a"))[i].Click();
        //some ways to come back to the previous page
    }

}
1
votes

Another solution without click

public void LoopLink() {
    int count = LinkElements.Count;

    for (int i = 0; i < count; i++)
    {
        var link = LinkElements[i];
        var href = link.GetAttribute("href");

        //ignore the anchor links without href attribute
        if (string.IsNullOrEmpty(href))
            continue;

        using (var webclient = new HttpClient())
        {
            var response = webclient.GetAsync(href).Result;
            Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
        }
    }
}
0
votes

Replace

hrefClick.Click();

with

item.Click()

inside your foreach() loop