简体   繁体   English

如何在 C# 中使用 Selenium?

[英]How do I use Selenium in C#?

Selenium . Selenium

I downloaded the C# client drivers and the IDE.我下载了 C# 客户端驱动程序和 IDE。 I managed to record some tests and successfully ran them from the IDE.我设法记录了一些测试并成功地从 IDE 运行它们。 But now I want to do that using C#.但现在我想使用 C# 来做到这一点。 I added all relevant DLL files (Firefox) to the project, but I don't have the Selenium class.我将所有相关的 DLL 文件(Firefox)添加到项目中,但我没有Selenium class。 Some Hello, World!一些你好,世界! would be nice.会好的。

From the Selenium Documentation :来自Selenium 文档

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();
    }
}
  1. Install the NuGet packet manager安装 NuGet 数据包管理器

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

  2. Create a C# console application创建 C# 控制台应用程序

  3. Right-click on the project → Manage NuGet Packages .右键单击项目 →管理 NuGet Packages Search for "Selenium" and install package Selenium.Support .搜索“Selenium”并安装 package Selenium.Support

You are done now, and you are ready to write your code:)你现在已经完成了,你已经准备好编写你的代码了:)

For code with Internet Explorer , download the Internet Explorer driver.对于Internet Explorer的代码,请下载 Internet Explorer 驱动程序。

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

  • Open 2.45 as its the latest release打开 2.45 作为其最新版本
  • Download IEDriverServer_x64_2.45.0.zip or IEDriverServer_Win32_2.45.0.zip下载 IEDriverServer_x64_2.45.0.zip 或 IEDriverServer_Win32_2.45.0.zip
  • Extract and simply paste the.exe file at any location, for example C:\提取并简单地将.exe 文件粘贴到任何位置,例如 C:\
  • Remember the path for further use.记住路径以供进一步使用。

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

My sample code:我的示例代码:

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

To set up the IDE for Selenium in conjunction with C# is to use Visual Studio Express.要将 IDE 设置为 Selenium 与 C# 一起使用 Visual Studio Express。 And you can use NUnit as the testing framework.您可以使用 NUnit 作为测试框架。 The below links provide you more details.以下链接为您提供更多详细信息。 It seems you have set up what is explained in the first link.看来您已经设置了第一个链接中解释的内容。 So check the second link for more details on how to create a basic script.因此,请查看第二个链接以获取有关如何创建基本脚本的更多详细信息。

How to setup C#, NUnit and Selenium client drivers on Visual Studio Express for Automated tests 如何在 Visual Studio Express 上设置 C#、NUnit 和 Selenium 客户端驱动程序以进行自动化测试

Creating a basic Selenium web driver test case using NUnit and C# 使用 NUnit 和 C# 创建基本的 Selenium web 驱动程序测试用例

Sample code from the above blog post:来自上述博客文章的示例代码:

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

            )

        }
    }

One of the things that I had a hard time finding was how to use PageFactory in C#.我很难找到的一件事是如何在 C# 中使用 PageFactory。 Especially for multiple IWebElements.特别是对于多个 IWebElements。 If you wish to use PageFactory, here are a few examples.如果你想使用 PageFactory,这里有几个例子。 Source: PageFactory.cs 来源:PageFactory.cs

To declare an HTML WebElement, use this inside the class file.要声明 HTML WebElement,请在 class 文件中使用它。

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;

Don't forget to instantiate the page object elements inside the constructor.不要忘记在构造函数中实例化页面 object 元素。

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

Now you can access that element in any of your files or methods.现在您可以在任何文件或方法中访问该元素。 Also, we can take relative paths from those elements if we ever wish to.此外,如果我们愿意,我们可以从这些元素中获取相对路径。 I prefer pagefactory because:我更喜欢 pagefactory,因为:

  • I don't ever need to call the driver directly using driver.FindElement(By.Id("id"))我不需要直接使用 driver.FindElement(By.Id("id")) 调用驱动程序
  • The objects are lazy initialized对象是惰性初始化

I use this to write my own wait-for-elements methods, WebElements wrappers to access only what I need to expose to the test scripts, and helps keeps things clean.我用它来编写我自己的等待元素方法,WebElements 包装器只访问我需要向测试脚本公开的内容,并帮助保持干净。

This makes life a lot easier if you have dynamic (autogerated) webelements like lists of data.如果您拥有动态(自动生成的)网络元素(如数据列表),这会使生活变得更加轻松。 You simply create a wrapper that will take the IWebElements and add methods to find the element you are looking for.您只需创建一个包装器,该包装器将采用 IWebElements 并添加方法来查找您要查找的元素。

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

C# C#

  1. First of all, download Selenium IDE for Firefox from the Selenium IDE . First of all, download Selenium IDE for Firefox from the Selenium IDE .

    Use and play around with it, test a scenario, record the steps, and then export it as a C# or Java project as per your requirement.使用并试用它,测试场景,记录步骤,然后根据您的要求将其导出为 C# 或 Java 项目。

    The code file contains code something like:代码文件包含如下代码:

     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. You need to get the Chrome driver from here .您需要从此处获取 Chrome 驱动程序。

  3. You need to get NuGet packages and necessary DLL files for the Selenium NuGet website.您需要为 Selenium Z20055252BAD325BE70C329DCEE76 网站获取 NuGet 软件包和必要的 DLL 文件。

  4. You need to understand the basics of Selenium from the Selenium documentation website.您需要从 Selenium 文档网站了解 Selenium 的基础知识。

That's all...就这样...

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();
    }
}
  1. You will need to install Microsoft Visual Studio community Edition您将需要安装 Microsoft Visual Studio 社区版
  2. Create a new project as Test Project of C#创建一个新项目作为 C# 的测试项目
  3. Add Selenium references from the NuGet Package Manager.从 NuGet Package 管理器中添加 Selenium 引用。 Then you will be all set.然后你就准备好了。
  4. Create a new class and use [Test Class] and [Test Method] annotations to run your script创建一个新的 class 并使用 [Test Class] 和 [Test Method] 注释来运行您的脚本
  5. You can refer to Run Selenium C# |可以参考运行 Selenium C# | Setup Selenium and C# |设置 Selenium 和 C# | Configure Selenium C# for more details.配置 Selenium C#了解更多详情。

Use the below code once you've added all the required C# libraries to the project in the references.将所有必需的 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();
        }

    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM