检查所有链接Selenium C#



我正在尝试自动测试网站上的所有链接。但问题是我的foreach循环在第一次点击后就停止了。

当我控制台日志属性时,它会写出所有链接,但在点击时不会这样做:)

这将注销所有链接。

 [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"));
            
        }
    }

但当我尝试Click()函数时,它只点击了第一个链接。

 [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"));
        }
    }

我还尝试了在每次点击后反向导航的方法,但也是无用和错误的:(

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

有什么建议吗?

您需要找到ALL链接。您正在使用的[FindsBy]返回一个链接,而不是列表。首先找到一个集合

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

编辑

请注意,简单地点击WebElements的列表可能会由于DOM刷新而返回StaleElement引用异常。使用for loop并查找元素运行时。

[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
    }
}

另一个无需点击的解决方案

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));
        }
    }
}

更换

hrefClick.Click();

带有

item.Click()

在foreach()循环中

最新更新