【问题标题】:check all links Selenium C#检查所有链接 Selenium C#
【发布时间】:2015-03-29 15:12:16
【问题描述】:

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

当我 Console.log 属性时,它会写出所有链接,但在单击时不会这样做:)

这会注销所有链接。

 [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();

有什么建议吗?

【问题讨论】:

    标签: c# selenium


    【解决方案1】:

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

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

    【讨论】:

    • 我也尝试过该解决方案,但 LinkElements 不会使用 Click() 方法。
    • 好吧,你不能以任何方式在特定场景中使用 foreach。它将通过StaleElement 引用异常。但是以编程方式,您应该能够
    • 嗯。将尝试理解您的意思:) 这是我使用 C# 和 Selenium 的第二天,所以我对此很陌生。
    • 查看我的编辑。我试图在那里解释。我遇到了同样的情况,这在selenium 中很常见
    • 我想我实际上理解了这里的问题,代码将我带到了第二页。可能需要更多的麻烦。但感谢您的解释和帮助。
    【解决方案2】:

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

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

    【讨论】:

      【解决方案3】:

      替换

      hrefClick.Click();
      

      item.Click()
      

      在你的 foreach() 循环中

      【讨论】:

      • 在第一个链接之后它仍然停止。 :)
      猜你喜欢
      • 1970-01-01
      • 2019-04-30
      • 2014-11-25
      • 1970-01-01
      • 2021-08-07
      • 1970-01-01
      • 2011-03-12
      • 2018-06-17
      • 2019-07-27
      相关资源
      最近更新 更多