一直忘記寫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