一直忘记写selenium的开始学习的过程,今天趁五一,天气有雨,写下这文章html
1.进入selnium官网,了解selenium1,2,grid的区别。下载c#相关的包(使用c#的人很是少)web
2.使用IED录制脚本,用C#导出,观察脚本的写法。固然须要在selenium官网下载IDE(firefox)chrome
2.1下载插件成功后会在firefox看到selenium IDE,点击c#
2.2使用IDE录制对www.google.com的搜索操做浏览器
2.3能够导出相应的c# remote control 或webdriver脚本ide
2.3.1使用selenium 1 (Remote control)记得须要启动 rc server,脚本才能运行学习
原理图:测试
主要代码:ui
using System; using System.Text; using System.Text.RegularExpressions; using System.Threading; using NUnit.Framework; using Selenium; namespace SeleniumTests { [TestFixture]//测试类 public class re { private ISelenium selenium; private StringBuilder verificationErrors; [SetUp]//测试准备(数据,方法) public void SetupTest() { selenium = new DefaultSelenium("localhost", 4444, "*chrome", "https://www.google.com.hk/"); selenium.Start(); verificationErrors = new StringBuilder(); } [TearDown]//测试资源复位 public void TeardownTest() { try { selenium.Stop(); } catch (Exception) { // Ignore errors if unable to close the browser } Assert.AreEqual("", verificationErrors.ToString()); } [Test]//测试 public void TheReTest() { selenium.Open("/"); selenium.Type("id=lst-ib", "SELENIUM"); } } }
2.3.2 使用selenium 2(selenium 1+webdriver)google
原理:利用浏览器native support来操做浏览器,由于firefox有浏览器原生组件webdriver.xpi,故不须要像IE,Chrome须要使用其余命令为浏览器native的调用
FirefoxDriver初始化成功以后,默认会从http://localhost:7055开始,而ChromeDriver则大概是http://localhost:46350
须要在vs references 引进相应的.dll(若是你建的solution为unitTest,须要应用nunit.framework.dll)
主要代码:
using System; using System.Text; using System.Text.RegularExpressions; using System.Threading; using NUnit.Framework; using OpenQA.Selenium; using OpenQA.Selenium.Firefox; using OpenQA.Selenium.Support.UI; namespace SeleniumTests { [TestFixture] public class Wb { private IWebDriver driver; private StringBuilder verificationErrors; private string baseURL; private bool acceptNextAlert = true; [SetUp] public void SetupTest() { driver = new FirefoxDriver(); baseURL = "https://www.google.com.hk/"; verificationErrors = new StringBuilder(); } [TearDown] public void TeardownTest() { try { driver.Quit(); } catch (Exception) { // Ignore errors if unable to close the browser } Assert.AreEqual("", verificationErrors.ToString()); } [Test] public void TheWbTest() { driver.Navigate().GoToUrl(baseURL + "/"); driver.FindElement(By.Id("lst-ib")).Clear(); driver.FindElement(By.Id("lst-ib")).SendKeys("SELENIUM"); } private bool IsElementPresent(By by) { try { driver.FindElement(by); return true; } catch (NoSuchElementException) { return false; } } private bool IsAlertPresent() { try { driver.SwitchTo().Alert(); return true; } catch (NoAlertPresentException) { return false; } } private string CloseAlertAndGetItsText() { try { IAlert alert = driver.SwitchTo().Alert(); string alertText = alert.Text; if (acceptNextAlert) { alert.Accept(); } else { alert.Dismiss(); } return alertText; } finally { acceptNextAlert = true; } } } }
能够说selenium自动化的基本脚本就完成了,能够run进行调试了,方法有:nunit/resharper