Selenium

Web element仍然使用OpenQA.Selenium.IWebElement, 本类库将Selenium原装支持的各浏览器统一为OnDriver, 并将常用操作封装。

在Visual Studio中,这意味着您需要安装TWO软件包:

> NuGet包“Selenium.WebDriver”,而且
> NuGet包“Selenium.Support

 OneDriver.cs

复制代码

using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium.IE;
using OpenQA.Selenium.Interactions;
using OpenQA.Selenium.Safari;
using OpenQA.Selenium.Support.UI;
using System;
using System.Collections.Generic;
using System.Linq;
//using QA = OpenQA.Selenium;
//using UI = OpenQA.Selenium.Support.UI;

namespace SeleniumWebDrivers
{
public class OneDriver
{
private IWebDriver wd = null;
private Browsers browser = Browsers.IE;
public OneDriver(Browsers theBrowser)
{
this.browser = theBrowser;
wd = InitWebDriver();
}

private IWebDriver InitWebDriver()
{
IWebDriver theDriver = null;
switch (this.browser)
{
case Browsers.IE:
{
InternetExplorerOptions _ieOptions = new InternetExplorerOptions();
_ieOptions.IntroduceInstabilityByIgnoringProtectedModeSettings = true;
theDriver = new InternetExplorerDriver(_ieOptions);
}; break;
case Browsers.Chrome:
{
theDriver = new ChromeDriver();
}; break;
case Browsers.Firefox:
{
theDriver = new FirefoxDriver();
}; break;
case Browsers.Safari:
{
theDriver = new SafariDriver();
}; break;
//case Browsers.PhantomJS:
// {
// theDriver = new QA.PhantomJS.PhantomJSDriver();
// }; break;
default:
{
InternetExplorerOptions _ieOptions = new InternetExplorerOptions();
_ieOptions.IntroduceInstabilityByIgnoringProtectedModeSettings = true;
theDriver = new InternetExplorerDriver(_ieOptions);
}; break;
}
return theDriver;
}

#region public members
/// <summary>
/// Effects throughout the life of web driver
/// Set once only if necessary
/// </summary>
/// <param name="seconds"></param>
public void ImplicitlyWait(double seconds)
{
wd.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(seconds);
}

/// <summary>
/// Wait for the expected condition is satisfied, return immediately
/// </summary>
/// <param name="expectedCondition"></param>
public void WaitForPage(string title)
{
WebDriverWait _wait = new WebDriverWait(wd, TimeSpan.FromSeconds(10));
_wait.Until((d) => { return d.Title.ToLower().StartsWith(title.ToLower()); });
//to do
}

/// <summary>
///
/// </summary>
/// <param name="we"></param>
public void WaitForElement(string id)
{
WebDriverWait _wait = new WebDriverWait(wd, TimeSpan.FromSeconds(10));
_wait.Until(condition: (d) => { return ExpectedConditions.ElementExists(By.Id(id)); });
}


/// <summary>
/// Load a new web page in current browser
/// </summary>
/// <param name="url"></param>
public void GoToUrl(string url)
{
wd.Navigate().GoToUrl(url);
}

public void Refresh()
{
wd.Navigate().Refresh();
}

public void Back()
{
wd.Navigate().Back();
}

public void Forward()
{
wd.Navigate().Forward();
}

/// <summary>
/// Get the url of current browser window
/// </summary>
/// <returns></returns>
public string GetUrl()
{
return wd.Url;
}

/// <summary>
/// Get page title of current browser window
/// </summary>
/// <returns></returns>
public string GetPageTitle()
{
return wd.Title;
}

/// <summary>
/// Get all cookies defined in the current page
/// </summary>
/// <returns></returns>
public Dictionary<string, string> GetAllCookies()
{
Dictionary<string, string> cookies = new Dictionary<string, string>();
switch (this.browser)
{
case Browsers.IE:
{
var allCookies = ((InternetExplorerDriver)wd).Manage().Cookies.AllCookies;
foreach (Cookie cookie in allCookies)
{
cookies[cookie.Name] = cookie.Value;
}
}; break;
case Browsers.Chrome:
{
var allCookies = ((ChromeDriver)wd).Manage().Cookies.AllCookies;
foreach (Cookie cookie in allCookies)
{
cookies[cookie.Name] = cookie.Value;
}
}; break;
case Browsers.Firefox:
{
var allCookies = ((FirefoxDriver)wd).Manage().Cookies.AllCookies;
foreach (Cookie cookie in allCookies)
{
cookies[cookie.Name] = cookie.Value;
}
}; break;
case Browsers.Safari:
{
var allCookies = ((SafariDriver)wd).Manage().Cookies.AllCookies;
foreach (Cookie cookie in allCookies)
{
cookies[cookie.Name] = cookie.Value;
}
}; break;
//case Browsers.PhantomJS:
// {
// var allCookies = ((QA.PhantomJS.PhantomJSDriver)wd).Manage().Cookies.AllCookies;
// foreach (QA.Cookie cookie in allCookies)
// {
// cookies[cookie.Name] = cookie.Value;
// }
// }; break;
default:
{
var allCookies = ((InternetExplorerDriver)wd).Manage().Cookies.AllCookies;
foreach (Cookie cookie in allCookies)
{
cookies[cookie.Name] = cookie.Value;
}
}; break;
}

return cookies;
}

/// <summary>
/// Delete all cookies from the page
/// </summary>
public void DeleteAllCookies()
{
switch (this.browser)
{
case Browsers.IE:
{
((InternetExplorerDriver)wd).Manage().Cookies.DeleteAllCookies();
}; break;
case Browsers.Chrome:
{
((ChromeDriver)wd).Manage().Cookies.DeleteAllCookies();
}; break;
case Browsers.Firefox:
{
((FirefoxDriver)wd).Manage().Cookies.DeleteAllCookies();
}; break;
case Browsers.Safari:
{
((SafariDriver)wd).Manage().Cookies.DeleteAllCookies();
}; break;
default:
{
((InternetExplorerDriver)wd).Manage().Cookies.DeleteAllCookies();
}; break;
}
}

/// <summary>
/// Set focus to a browser window with a specified title
/// </summary>
/// <param name="title"></param>
/// <param name="exactMatch"></param>
public void GoToWindow(string title, bool exactMatch)
{
string theCurrent = wd.CurrentWindowHandle;
IList<string> windows = wd.WindowHandles;
if (exactMatch)
{
foreach (var window in windows)
{
wd.SwitchTo().Window(window);
if (wd.Title.ToLower() == title.ToLower())
{
return;
}
}
}
else
{
foreach (var window in windows)
{
wd.SwitchTo().Window(window);
if (wd.Title.ToLower().Contains(title.ToLower()))
{
return;
}
}
}

wd.SwitchTo().Window(theCurrent);
}

/// <summary>
/// Set focus to a frame with a specified name
/// </summary>
/// <param name="name"></param>
public void GoToFrame(string name)
{
IWebElement theFrame = null;
var frames = wd.FindElements(By.TagName("iframe"));
foreach (var frame in frames)
{
if (frame.GetAttribute("name").ToLower() == name.ToLower())
{
theFrame = (IWebElement)frame;
break;
}
}
if (theFrame != null)
{
wd.SwitchTo().Frame(theFrame);
}
}

public void GoToFrame(IWebElement frame)
{
wd.SwitchTo().Frame(frame);
}

/// <summary>
/// Switch to default after going to a frame
/// </summary>
public void GoToDefault()
{
wd.SwitchTo().DefaultContent();
}

/// <summary>
/// Get the alert text
/// </summary>
/// <returns></returns>
public string GetAlertString()
{
string theString = string.Empty;
IAlert alert = null;
alert = wd.SwitchTo().Alert();
if (alert != null)
{
theString = alert.Text;
}
return theString;
}

/// <summary>
/// Accepts the alert
/// </summary>
public void AlertAccept()
{
IAlert alert = null;
alert = wd.SwitchTo().Alert();
if (alert != null)
{
alert.Accept();
}
}

/// <summary>
/// Dismisses the alert
/// </summary>
public void AlertDismiss()
{
IAlert alert = null;
alert = wd.SwitchTo().Alert();
if (alert != null)
{
alert.Dismiss();
}
}

/// <summary>
/// Move vertical scroll bar to bottom for the page
/// </summary>
public void PageScrollToBottom()
{
var js = "document.documentElement.scrollTop=10000";
switch (this.browser)
{
case Browsers.IE:
{
((InternetExplorerDriver)wd).ExecuteScript(js, null);
}; break;
case Browsers.Chrome:
{
((ChromeDriver)wd).ExecuteScript(js, null);
}; break;
case Browsers.Firefox:
{
((FirefoxDriver)wd).ExecuteScript(js, null);
}; break;
case Browsers.Safari:
{
((SafariDriver)wd).ExecuteScript(js, null);
}; break;
//case Browsers.PhantomJS:
// {
// ((QA.PhantomJS.PhantomJSDriver)wd).ExecuteScript(js, null);
// }; break;
default:
{
((InternetExplorerDriver)wd).ExecuteScript(js, null);
}; break;
}
}

/// <summary>
/// Move horizontal scroll bar to right for the page
/// </summary>
public void PageScrollToRight()
{
var js = "document.documentElement.scrollLeft=10000";
switch (this.browser)
{
case Browsers.IE:
{
((InternetExplorerDriver)wd).ExecuteScript(js, null);
}; break;
case Browsers.Chrome:
{
((ChromeDriver)wd).ExecuteScript(js, null);
}; break;
case Browsers.Firefox:
{
((FirefoxDriver)wd).ExecuteScript(js, null);
}; break;
case Browsers.Safari:
{
((SafariDriver)wd).ExecuteScript(js, null);
}; break;
//case Browsers.PhantomJS:
// {
// ((QA.PhantomJS.PhantomJSDriver)wd).ExecuteScript(js, null);
// }; break;
default:
{
((InternetExplorerDriver)wd).ExecuteScript(js, null);
}; break;
}
}

/// <summary>
/// Move vertical scroll bar to bottom for an element
/// </summary>
/// <param name="element"></param>
public void ElementScrollToBottom(IWebElement element)
{
string id = element.GetAttribute("id");
string name = element.GetAttribute("name");
var js = "";
if (!string.IsNullOrWhiteSpace(id))
{
js = "document.getElementById('" + id + "').scrollTop=10000";
}
else if (!string.IsNullOrWhiteSpace(name))
{
js = "document.getElementsByName('" + name + "')[0].scrollTop=10000";
}
switch (this.browser)
{
case Browsers.IE:
{
((InternetExplorerDriver)wd).ExecuteScript(js, null);
}; break;
case Browsers.Chrome:
{
((ChromeDriver)wd).ExecuteScript(js, null);
}; break;
case Browsers.Firefox:
{
((FirefoxDriver)wd).ExecuteScript(js, null);
}; break;
case Browsers.Safari:
{
((SafariDriver)wd).ExecuteScript(js, null);
}; break;
//case Browsers.PhantomJS:
// {
// ((QA.PhantomJS.PhantomJSDriver)wd).ExecuteScript(js, null);
// }; break;
default:
{
((InternetExplorerDriver)wd).ExecuteScript(js, null);
}; break;
}
}

/// <summary>
/// Get a screen shot of the current window
/// </summary>
/// <param name="savePath"></param>
public void TakeScreenshot(string savePath)
{
Screenshot theScreenshot = null;
switch (this.browser)
{
case Browsers.IE:
{
theScreenshot = ((InternetExplorerDriver)wd).GetScreenshot();
}; break;
case Browsers.Chrome:
{
theScreenshot = ((ChromeDriver)wd).GetScreenshot();
}; break;
case Browsers.Firefox:
{
theScreenshot = ((FirefoxDriver)wd).GetScreenshot();
}; break;
case Browsers.Safari:
{
theScreenshot = ((SafariDriver)wd).GetScreenshot();
}; break;
//case Browsers.PhantomJS:
// {
// theScreenshot = ((QA.PhantomJS.PhantomJSDriver)wd).GetScreenshot();
// }; break;
default:
{
theScreenshot = ((InternetExplorerDriver)wd).GetScreenshot();
}; break;
}
if (theScreenshot != null)
{
theScreenshot.SaveAsFile(savePath, ScreenshotImageFormat.Jpeg);
}
}

/// <summary>
/// Find the element of a specified id
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public IWebElement FindElementById(string id)
{
IWebElement theElement = null;
theElement = (IWebElement)wd.FindElement(By.Id(id));
return theElement;
}

/// <summary>
/// Find the element of a specified name
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
public IWebElement FindElementByName(string name)
{
IWebElement theElement = null;
theElement = (IWebElement)wd.FindElement(By.Name(name));
return theElement;
}

/// <summary>
/// Find the element by xpath
/// </summary>
/// <param name="xpath"></param>
/// <returns></returns>
public IWebElement FindElementByXPath(string xpath)
{
IWebElement theElement = null;
theElement = (IWebElement)wd.FindElement(By.XPath(xpath));
return theElement;
}

public IWebElement FindElementByLinkText(string text)
{
IWebElement theElement = null;
try
{
theElement = wd.FindElement(By.LinkText(text));
}
catch { }
return theElement;
}

public IList<IWebElement> FindElementsByLinkText(string text)
{
IList<IWebElement> theElement = null;
theElement = (IList<IWebElement>)wd.FindElements(By.LinkText(text));
return theElement;
}

public IList<IWebElement> FindElementsByPartialLinkText(string text)
{
IList<IWebElement> theElement = null;
theElement = (IList<IWebElement>)wd.FindElements(By.PartialLinkText(text));
return theElement;
}

public IList<IWebElement> FindElementsByClassName(string clsName)
{
IList<IWebElement> theElement = null;
theElement = (IList<IWebElement>)wd.FindElements(By.ClassName(clsName));
return theElement;
}

public IList<IWebElement> FindElementsByTagName(string tagName)
{
IList<IWebElement> theElement = null;
theElement = (IList<IWebElement>)wd.FindElements(By.TagName(tagName));
return theElement;
}

public IList<IWebElement> FindElementsByCssSelector(string css)
{
IList<IWebElement> theElement = null;
theElement = (IList<IWebElement>)wd.FindElements(By.CssSelector(css));
return theElement;
}

public IList<IWebElement> FindElementsByXPathName(string xpath)
{
IList<IWebElement> theElement = null;
theElement = (IList<IWebElement>)wd.FindElements(By.XPath(xpath));
return theElement;
}

/// <summary>
/// Executes javascript
/// </summary>
/// <param name="js"></param>
public void ExecuteJS(string js)
{
switch (this.browser)
{
case Browsers.IE:
{
((InternetExplorerDriver)wd).ExecuteScript(js, null);
}; break;
case Browsers.Chrome:
{
((ChromeDriver)wd).ExecuteScript(js, null);
}; break;
case Browsers.Firefox:
{
((FirefoxDriver)wd).ExecuteScript(js, null);
}; break;
case Browsers.Safari:
{
((SafariDriver)wd).ExecuteScript(js, null);
}; break;
//case Browsers.PhantomJS:
// {
// ((QA.PhantomJS.PhantomJSDriver)wd).ExecuteScript(js, null);
// }; break;
default:
{
((InternetExplorerDriver)wd).ExecuteScript(js, null);
}; break;
}
}

public void ClickElement(IWebElement element)
{
(new Actions(wd)).Click(element).Perform();
}

public void DoubleClickElement(IWebElement element)
{
(new Actions(wd)).DoubleClick(element).Perform();
}

public void ClickAndHoldOnElement(IWebElement element)
{
(new Actions(wd)).ClickAndHold(element).Perform();
}

public void ContextClickOnElement(IWebElement element)
{
(new Actions(wd)).ContextClick(element).Perform();
}

public void DragAndDropElement(IWebElement source, IWebElement target)
{
(new Actions(wd)).DragAndDrop(source, target).Perform();
}

public void SendKeysToElement(IWebElement element, string text)
{
(new Actions(wd)).SendKeys(element, text).Perform();
}

/// <summary>
/// Quit this server, close all windows associated to it
/// </summary>
public void Cleanup()
{
wd.Quit();
}
#endregion
}

public enum Browsers
{
IE,
Firefox,
Chrome,
Safari,
PhantomJS
}
}

复制代码
原文地址:https://www.cnblogs.com/zhaiganggang/p/13804231.html