【问题标题】:How to iterate a list of IWebElements and store in array and then print in console c#如何迭代 IWebElements 列表并存储在数组中,然后在控制台 c# 中打印
【发布时间】:2017-12-11 18:29:04
【问题描述】:

我正在学习 c# 并试图了解数组。我在 selenium c# 中实际使用数组并面临一种情况,我无法将它们的值迭代存储到数组中。我的意图是,我想存储数组中的所有价格,然后用for循环在控制台中一一迭代。

namespace OneDimensionalarray

{

class Program
{
    static void Main(string[] args)
    {

        IWebDriver driver = null;

        driver = new ChromeDriver();

        driver.Manage().Window.Maximize();

        driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(10);

        driver.Navigate().GoToUrl("http://www.shopclues.com/");  

        driver.FindElement(By.XPath("//input[@id='autocomplete']")). SendKeys("Lenovo");

        driver.FindElement(By.XPath("//span[@id='search']/a")).Click();

        IList<IWebElement> mobileprice = driver.FindElements(By.XPath("//span[@class='p_price']"));


 //I want to store mobiles prices into an array and then print in the console.

        int price = mobileprice.Count;

        int[] prices = new int[price];

        for (int i = 0; i < prices.Length; i++)
        {
            Console.WriteLine(price);
            Console.Read();
        }

    }

    }
}

【问题讨论】:

  • 你卡在哪里了?你看到任何错误吗?在哪一行?
  • 如果您是 C# 新手,我的一个建议是了解泛型和 List&lt;T&gt;。您可以将此类型视为类似于数组,但它会在您向其中添加元素时调整大小。
  • 感谢您的回复。我没有看到任何错误,也无法在控制台中读取价格。
  • 我的意图是在数组中获取 mobileprices 并使用 for 循环在控制台中打印价格,但没有显示
  • 根据您的代码,您将 mobileprice.Count 存储在一个变量中。然后,您将创建一个您永远不会使用的prices 数组,除非调用prices.Length,它始终是price 的值。在你的循环中,你没有访问你的数组。为此,您需要执行prices[i] 之类的操作,但这不会有太大帮助,因为您从未真正在数组中放置任何值。

标签: c# arrays linq selenium


【解决方案1】:

要将所有价格存储在数组中,然后使用 for 循环在控制台中逐个迭代,您可以使用以下代码块:

IList<IWebElement> mobileprice = driver.FindElements(By.XPath("//span[@class='p_price']"));
foreach (IWebElement price in mobileprice )
    Console.WriteLine(price.GetAttribute("innerHTML"));

【讨论】:

    【解决方案2】:

    您正在创建数组,但在遍历它之前没有填充任何内容。

    尝试(这不使用数组 - 不需要它......)

    //I want to store mobiles prices into an array and then print in the console.
    foreach (IWebElement priceElement in mobileprice )
    {
      Console.WriteLine(priceElement.getText());
      Console.Read();
    }
    

    【讨论】:

      猜你喜欢
      • 2022-01-25
      • 2020-01-14
      • 2023-03-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-28
      • 1970-01-01
      相关资源
      最近更新 更多