【问题标题】:How do I use Selenium in C#?如何在 C# 中使用 Selenium?
【发布时间】:2011-09-14 02:42:19
【问题描述】:

Selenium.

我下载了 C# 客户端驱动程序和 IDE。我设法记录了一些测试并成功地从 IDE 运行它们。但现在我想使用 C# 来做到这一点。我将所有相关的 DLL 文件 (Firefox) 添加到项目中,但我没有 Selenium 类。一些 Hello, World! 会很好。

【问题讨论】:

  • 我想你看过这个? seleniumhq.org/docs/…
  • 你试过谷歌搜索吗?当然,有很多——也许是大部分? - 与 Java 相关的 Selenium 内容,但肯定也有基本的 C#/VS/Selenium 教程可以回答您的问题。
  • 我下载了 C# 驱动程序和 IDE -> IDE 是什么意思?它是用来编写 C# selenium 代码的吗?比如 Visual Studio。或者,是 Selenium IDE?
  • 猜猜你将使用 Visual Studio 编写 Selenium C# 代码并管理代码和构建。

标签: c# selenium firefox webdriver automated-tests


【解决方案1】:

来自Selenium Documentation

using OpenQA.Selenium.Firefox;
using OpenQA.Selenium;

class GoogleSuggest
{
    static void Main(string[] args)
    {
        IWebDriver driver = new FirefoxDriver();

        //Notice navigation is slightly different than the Java version
        //This is because 'get' is a keyword in C#
        driver.Navigate().GoToUrl("http://www.google.com/");
        IWebElement query = driver.FindElement(By.Name("q"));
        query.SendKeys("Cheese");
        System.Console.WriteLine("Page title is: " + driver.Title);
        driver.Quit();
    }
}

【讨论】:

    【解决方案2】:
    1. 安装 NuGet 数据包管理器

      下载链接:https://visualstudiogallery.msdn.microsoft.com/27077b70-9dad-4c64-adcf-c7cf6bc9970c

    2. 创建一个 C# 控制台应用程序

    3. 右键单击项目 → 管理 NuGet 包。 搜索“Selenium”并安装包Selenium.Support

    你现在已经完成了,你可以开始编写你的代码了 :)

    对于带有Internet Explorer 的代码,请下载 Internet Explorer 驱动程序。

    链接:http://selenium-release.storage.googleapis.com/index.html

    • 打开 2.45 作为其最新版本
    • 下载 IEDriverServer_x64_2.45.0.zip 或 IEDriverServer_Win32_2.45.0.zip
    • 解压 .exe 文件并将其粘贴到任意位置,例如 C:\
    • 记住路径以供进一步使用。

    整体参考链接:Selenium 2.0 WebDriver with Visual Studio, C#, & IE – Getting Started

    我的示例代码:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using OpenQA.Selenium;
    using OpenQA.Selenium.Support.UI;
    using OpenQA.Selenium.IE;
    
    namespace Selenium_HelloWorld
    {
        class Program
        {
            static void Main(string[] args)
            {
                IWebDriver driver = new InternetExplorerDriver("C:\\");
                driver.Navigate().GoToUrl("http://108.178.174.137");
                driver.Manage().Window.Maximize();
                driver.FindElement(By.Id("inputName")).SendKeys("apatra");
                driver.FindElement(By.Id("inputPassword")).SendKeys("asd");
                driver.FindElement(By.Name("DoLogin")).Click();
    
                string output = driver.FindElement( By.XPath(".//*[@id='tab-general']/div/div[2]/div[1]/div[2]/div/strong")).Text;
    
                if (output != null  )
                {
                    Console.WriteLine("Test Passed :) ");
                }
                else
                {
                    Console.WriteLine("Test Failed");
                }
            }
        }
    }
    

    【讨论】:

      【解决方案3】:

      结合 C# 设置 Selenium IDE 是使用 Visual Studio Express。您可以使用 NUnit 作为测试框架。以下链接为您提供更多详细信息。看来您已经设置了第一个链接中解释的内容。因此,请查看第二个链接以获取有关如何创建基本脚本的更多详细信息。

      How to setup C#, NUnit and Selenium client drivers on Visual Studio Express for Automated tests

      Creating a basic Selenium web driver test case using NUnit and C#

      来自上述博文的示例代码:

      using System;
      using Microsoft.VisualStudio.TestTools.UnitTesting;
      // Step a
      using OpenQA.Selenium;
      using OpenQA.Selenium.Support;
      using OpenQA.Selenium.Firefox;
      using NUnit.Framework;
      
      namespace NUnitSelenium
      {
          [TestFixture]
          public class UnitTest1
          {
              [SetUp]
              public void SetupTest()
              {
              }
      
              [Test]
              public void Test_OpeningHomePage()
              {
                  // Step b - Initiating webdriver
                  IWebDriver driver = new FirefoxDriver();
                  // Step c: Making driver to navigate
                  driver.Navigate().GoToUrl("http://docs.seleniumhq.org/");
      
                  // Step d
                  IWebElement myLink = driver.FindElement(By.LinkText("Download"));
                  myLink.Click();
      
                  // Step e
                  driver.Quit();
      
                  )
      
              }
          }
      

      【讨论】:

      • 多余的“)”是干什么用的?
      【解决方案4】:

      我很难找到的一件事是如何在 C# 中使用 PageFactory。特别是对于多个 IWebElements。如果你想使用 PageFactory,这里有几个例子。 Source: PageFactory.cs

      要声明一个 HTML WebElement,请在类文件中使用它。

      private const string _ID ="CommonIdinHTML";
      [FindsBy(How = How.Id, Using = _ID)]
      private IList<IWebElement> _MultipleResultsByID;
      
      private const string _ID2 ="IdOfElement";
      [FindsBy(How = How.Id, Using = _ID2)]
      private IWebElement _ResultById;
      

      不要忘记在构造函数中实例化页面对象元素。

      public MyClass(){
          PageFactory.InitElements(driver, this);
      }
      

      现在您可以在任何文件或方法中访问该元素。此外,如果我们愿意,我们可以从这些元素中获取相对路径。我更喜欢 pagefactory,因为:

      • 我不需要直接使用 driver.FindElement(By.Id("id")) 调用驱动程序
      • 对象是lazy initialized

      我用它来编写自己的等待元素方法,WebElements 包装器只访问我需要向测试脚本公开的内容,并帮助保持干净。

      如果您拥有动态(自动生成的)网络元素(例如数据列表),这会让生活变得更轻松。您只需创建一个包装器,该包装器将采用 IWebElements 并添加方法来查找您要查找的元素。

      【讨论】:

        【解决方案5】:
        FirefoxDriverService service = FirefoxDriverService.CreateDefaultService(@"D:\DownloadeSampleCode\WordpressAutomation\WordpressAutomation\Selenium", "geckodriver.exe");
        service.Port = 64444;
        service.FirefoxBinaryPath = @"C:\Program Files (x86)\Mozilla Firefox\firefox.exe";
        Instance = new FirefoxDriver(service); 
        

        【讨论】:

        • 请解释你的答案。这里不鼓励仅使用代码的答案,因为它们不教任何东西——它们只是鼓励复制粘贴编码。您可以使用答案下方的编辑链接添加其他信息。谢谢!
        【解决方案6】:

        C#

        1. 首先,从Selenium IDE 下载 Selenium IDE for Firefox。

          使用并试用它,测试场景,记录步骤,然后根据您的要求将其导出为 C# 或 Java 项目。

          代码文件包含如下代码:

           using System;
           using System.IO;
           using Microsoft.VisualStudio.TestTools.UnitTesting;
           using OpenQA.Selenium;
           using OpenQA.Selenium.Chrome;
          
           // Add this name space to access WebDriverWait
           using OpenQA.Selenium.Support.UI;
          
           namespace MyTest
           {
               [TestClass]
               public class MyTest
               {
                   public static IWebDriver Driver = null;
          
                   // Use TestInitialize to run code before running each test
                   [TestInitialize()]
                   public void MyTestInitialize()
                   {
                       try
                       {
                           string path = Path.GetFullPath(""); // Copy the Chrome driver to the debug
                                                               // folder in the bin or set path accordingly
                           Driver = new ChromeDriver(path);
                       }
                       catch (Exception ex)
                       {
                           string error = ex.Message;
                       }
                   }
          
                   // Use TestCleanup to run code after each test has run
                   [TestCleanup()]
                   public void MyCleanup()
                   {
                       Driver.Quit();
                   }
          
                   [TestMethod]
                   public void MyTestMethod()
                   {
                       try
                       {
                           string url = "http://www.google.com";
                           Driver.Navigate().GoToUrl(url);
          
                           IWait<IWebDriver> wait = new WebDriverWait(Driver, TimeSpan.FromSeconds(30.00)); // Wait in Selenium
                           wait.Until(ExpectedConditions.PresenceOfAllElementsLocatedBy(By.XPath(@"//*[@id='lst - ib']")));
          
                           var txtBox = Driver.FindElement(By.XPath(@"//*[@id='lst - ib']"));
                           txtBox.SendKeys("Google Office");
                           var btnSearch = Driver.FindElement(By.XPath("//*[@id='tsf']/div[2]/div[3]/center/input[1]"));
                           btnSearch.Click();
          
                           System.Threading.Thread.Sleep(5000);
                       }
                       catch (Exception ex)
                       {
                           string error = ex.Message;
                       }
                   }
               }
           }
          
        2. 您需要从here 获取 Chrome 驱动程序。

        3. 您需要为 Selenium NuGet 网站获取 NuGet 包和必要的 DLL 文件。

        4. 您需要从 Selenium 文档网站了解 Selenium 的基础知识。

        就是这样……

        【讨论】:

          【解决方案7】:
          using System;
          using Microsoft.VisualStudio.TestTools.UnitTesting;
          using OpenQA.Selenium;
          using OpenQA.Selenium.Interactions;
          using OpenQA.Selenium.Support.UI;
          using SeleniumAutomationFramework.CommonMethods;
          using System.Text;
          
          [TestClass]
          public class SampleInCSharp
          {
              public static IWebDriver driver = Browser.CreateWebDriver(BrowserType.chrome);
          
              [TestMethod]
              public void SampleMethodCSharp()
              {
                  driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(5));
                  driver.Url = "http://www.store.demoqa.com";
                  driver.Manage().Window.Maximize();
          
                  driver.FindElement(By.XPath(".//*[@id='account']/a")).Click();
                  driver.FindElement(By.Id("log")).SendKeys("kalyan");
                  driver.FindElement(By.Id("pwd")).SendKeys("kalyan");
                  driver.FindElement(By.Id("login")).Click();
          
                  WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
                  IWebElement myDynamicElement = wait.Until<IWebElement>(d => d.FindElement(By.LinkText("Log out")));
          
                  Actions builder = new Actions(driver);
                  builder.MoveToElement(driver.FindElement(By.XPath(".//*[@id='menu-item-33']/a"))).Build().Perform();
                  driver.FindElement(By.XPath(".//*[@id='menu-item-37']/a")).Click();
                  driver.FindElement(By.ClassName("wpsc_buy_button")).Click();
                  driver.FindElement(By.XPath(".//*[@id='fancy_notification_content']/a[1]")).Click();
                  driver.FindElement(By.Name("quantity")).Clear();
                  driver.FindElement(By.Name("quantity")).SendKeys("10");
                  driver.FindElement(By.XPath("//*[@id='checkout_page_container']/div[1]/a/span")).Click();
                  driver.FindElement(By.ClassName("account_icon")).Click();
                  driver.FindElement(By.LinkText("Log out")).Click();
                  driver.Close();
              }
          }
          

          【讨论】:

            【解决方案8】:
            1. 您需要安装 Microsoft Visual Studio 社区版
            2. 创建一个新项目作为 C# 的 Test Project
            3. 从 NuGet 包管理器添加 Selenium 引用。然后你就准备好了。
            4. 创建一个新类并使用 [Test Class] 和 [Test Method] 注释来运行您的脚本
            5. 您可以参考Run Selenium C# | Setup Selenium and C# | Configure Selenium C#了解更多详情。

            【讨论】:

              【解决方案9】:

              将所有必需的 C# 库添加到引用中的项目后,请使用以下代码。

              using OpenQA.Selenium;
              using OpenQA.Selenium.Firefox;
              namespace SeleniumWithCsharp
              {
                  class Test
                  {
                      public IWebDriver driver;
              
              
                      public void openGoogle()
                      {
                          // creating Browser Instance
                          driver = new FirefoxDriver();
                          //Maximizing the Browser
                          driver.Manage().Window.Maximize();
                          // Opening the URL
                          driver.Navigate().GoToUrl("http://google.com");
                          driver.FindElement(By.Id("lst-ib")).SendKeys("Hello World");
                          driver.FindElement(By.Name("btnG")).Click();
                      }
              
                      static void Main()
                      {
                          Test test = new Test();
                          test.openGoogle();
                      }
              
                  }
              }
              

              【讨论】:

                猜你喜欢
                • 1970-01-01
                • 2022-01-12
                • 1970-01-01
                • 1970-01-01
                • 2020-08-25
                • 2014-01-10
                • 1970-01-01
                • 2018-09-22
                • 2021-05-05
                相关资源
                最近更新 更多