如何在C#中使用Selenium?

| 硒。 我下载了C#客户端驱动程序和IDE。我设法记录了一些测试,并成功地从IDE中运行了它们。但是现在我想使用C#做到这一点。我将所有相关的DLL(Firefox)添加到了项目中,但是我没有
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();
    }
}
    
         安装Nuget数据包管理器 下载链接:https://visualstudiogallery.msdn.microsoft.com/27077b70-9dad-4c64-adcf-c7cf6bc9970c 创建一个可视的C#控制台应用程序 右键单击项目->管理Nuget包。 搜索\“ Selenium \”并安装软件包
Selenium.Support
现在完成,您就可以编写代码了:) 对于使用IE下载的代码,即驱动程序 链接:http://selenium-release.storage.googleapis.com/index.html 打开2.45,因为它是最新版本 下载IEDriverServer_x64_2.45.0.zip或IEDriverServer_Win32_2.45.0.zip 提取.exe文件并将其粘贴到任何位置,例如C:\\ 记住进一步使用的路径。 总体参考链接:http://www.joecolantonio.com/2012/07/31/getting-started-using-selenium-2-0-webdriver-for-ie-in-visual-studio-c/ 我的示例代码:
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\");
            }
        }
    }
}
    
        与c#一起设置ide硒的方法是使用Visual Studio Express。而且您可以将nUnit作为测试框架。以下链接为您提供了更多详细信息。看来您已经设置了第一个链接中说明的内容。因此,请查看第二个链接以获取有关如何创建基本脚本的更多详细信息。 如何在VSExpress上设置C#,nUnit和Selenium客户端驱动程序以进行自动化测试 使用Nunit和C#创建Basic Selenium Web驱动程序测试用例 以上博客的示例代码
    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();

        )
       }
}
    
        我知道这是一个比较老的问题,但我想我会将这些信息提供给其他人。 我很难找到的一件事是如何在C#中使用PageFactory。特别是对于多个IWebElement。如果您想使用PageFactory,请参考以下示例。资料来源: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 \”))直接调用驱动程序 对象是惰性初始化的 我用它来编写自己的等待元素方法,WebElements包装器仅访问我需要暴露给测试脚本的内容,并有助于保持环境整洁。 如果您拥有动态(自动)网络元素(如数据列表),这将使工作变得更加轻松。您只需创建一个包装器即可,该包装器将使用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# 首先,从Selenium IDE下载适用于Firefox的Selenium IDE。 使用并试用它,然后测试场景,记录步骤,然后根据需要将其导出为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));                    // Waiter 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;
        }
    }
}
}
您需要从这里获取chrome驱动程序 您需要获取硒nuget网站的金块软件包和必要的dll 您需要从Selenium文档网站了解Selenium的基础知识 就这样 ...     
        
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();
        }
}
    
        在参考中将所有必需的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();
        }

    }
}
    

要回复问题请先登录注册