C#Selenium WebDriver备忘录

初始化
cs 复制代码
//谷歌浏览器
using OpenQA.Selenium.Chrome;
IWebDriver driver = new ChromeDriver();
//火狐浏览器
using OpenQA.Selenium.Firefox;
IWebDriver driver = new FirefoxDriver();
// PhantomJS浏览器
using OpenQA.Selenium.PhantomJS;
IWebDriver driver = new PhantomJSDriver();
// IE浏览器
using OpenQA.Selenium.IE;
IWebDriver driver = new InternetExplorerDriver();
// Edge浏览器
using OpenQA.Selenium.Edge;
IWebDriver driver = new EdgeDriver();
定位标签方法
cs 复制代码
this.driver.FindElement(By.ClassName("className"));
this.driver.FindElement(By.CssSelector("css"));
this.driver.FindElement(By.Id("id"));
this.driver.FindElement(By.LinkText("text"));
this.driver.FindElement(By.Name("name"));
this.driver.FindElement(By.PartialLinkText("pText"));
this.driver.FindElement(By.TagName("input"));
this.driver.FindElement(By.XPath("//*[@id='editor']"));
// 查找多个元素
IReadOnlyCollection<IWebElement> anchors = 
this.driver.FindElements(By.TagName("a"));
//在另一个元素中搜索一个元素
var div = this.driver.FindElement(By.TagName("div"))
.FindElement(By.TagName("a"));
基本浏览器操作
cs 复制代码
// 导航到页面
this.driver.Navigate().GoToUrl(@"http://google.com");
// 获取页面的标题
string title = this.driver.Title;
// 获取当前URL
string url = this.driver.Url;
// 获取当前页面的HTML源
string html = this.driver.PageSource;
基本要素操作
cs 复制代码
IWebElement element = driver.FindElement(By.Id("id"));
element.Click();
element.SendKeys("someText");
element.Clear();
element.Submit();
string innerText = element.Text;
bool isEnabled = element.Enabled;
bool isDisplayed = element.Displayed;
bool isSelected = element.Selected;
IWebElement element = driver.FindElement(By.Id("id"));
SelectElement select = new SelectElement(element);
select.SelectByIndex(1);
select.SelectByText("Ford");
select.SelectByValue("ford"); 
select.DeselectAll();
select.DeselectByIndex(1);
select.DeselectByText("Ford");
select.DeselectByValue("ford");
IWebElement selectedOption = select.SelectedOption;
IList<IWebElement> allSelected = 
select.AllSelectedOptions;
bool isMultipleSelect = select.IsMultiple;
高级元素操作
cs 复制代码
// 拖放
IWebElement element = driver.FindElement(
By.XPath("//*[@id='project']/p[1]/div/div[2]"));
Actions move = new Actions(driver);
move.DragAndDropToOffset(element, 30, 0).Perform();
// 如何检查元素是否可见
Assert.IsTrue(driver.FindElement(
By.XPath("//*[@id='tve_editor']/div")).Displayed);
//上传文件
IWebElement element = 
driver.FindElement(By.Id("RadUpload1file0"));
String filePath = 
@"D:\WebDriver.Series.Tests\\WebDriver.xml";
element.SendKeys(filePath);
// 滚动焦点以控制
IWebElement link = 
driver.FindElement(By.PartialLinkText("Previous post"));
string js = 
string.Format("window.scroll(0, {0});", link.Location.Y);
((IJavaScriptExecutor)driver).ExecuteScript(js);
link.Click();
// 拍摄元素截图
IWebElement element = 
driver.FindElement(By.XPath("//*[@id='tve_editor']/div"));
var cropArea = new Rectangle(element.Location, 
element.Size);
var bitmap = bmpScreen.Clone(cropArea, 
bmpScreen.PixelFormat);
bitmap.Save(fileName);
// 关注控件
IWebElement link = 
driver.FindElement(By.PartialLinkText("Previous post"));
// 等待图元的可见性
WebDriverWait wait = new WebDriverWait(driver, 
TimeSpan.FromSeconds(30));
wait.Until(
ExpectedConditions.VisibilityOfAllElementsLocatedBy(
By.XPath("//*[@id='tve_editor']/div[2]/div[2]/div/div")));
高级浏览器操作
cs 复制代码
// 处理JavaScript弹出窗口
IAlert a = driver.SwitchTo().Alert();
a.Accept();
a.Dismiss();
// 在浏览器窗口或选项卡之间切换
ReadOnlyCollection<string> windowHandles = driver.WindowHandles;
string firstTab = windowHandles.First();
string lastTab = windowHandles.Last();
driver.SwitchTo().Window(lastTab);
// 历史记录
this.driver.Navigate().Back();
this.driver.Navigate().Refresh();
this.driver.Navigate().Forward();
// Option 1.
link.SendKeys(string.Empty);
// Option 2.
((IJavaScriptExecutor)driver).ExecuteScript("arguments[0].focus();", 
link);
// 最大化窗口
this.driver.Manage().Window.Maximize();
// 添加新cookie
Cookie cookie = new OpenQA.Selenium.Cookie("key", "value");
this.driver.Manage().Cookies.AddCookie(cookie);
// 获取所有cookie
var cookies = this.driver.Manage().Cookies.AllCookies;
//按名称删除cookie
this.driver.Manage().Cookies.DeleteCookieNamed("CookieName");
// 删除所有cookies
this.driver.Manage().Cookies.DeleteAllCookies();
//全屏截图
Screenshot screenshot = ((ITakesScreenshot)driver).GetScreenshot();
screenshot.SaveAsFile(@"pathToImage", ImageFormat.Png);
// 等待页面通过JavaScript完全加载
WebDriverWait wait = new WebDriverWait(this.driver, 
TimeSpan.FromSeconds(30));
wait.Until((x) =>
{
 return ((IJavaScriptExecutor)this.driver).ExecuteScript(
"return document.readyState").Equals("complete");
});
// 切换到帧
this.driver.SwitchTo().Frame(1);
this.driver.SwitchTo().Frame("frameName");
IWebElement element = this.driver.FindElement(By.Id("id"));
this.driver.SwitchTo().Frame(element);
// 切换到默认文档
this.driver.SwitchTo().DefaultContent();
高级浏览器配置
cs 复制代码
// Firefox配置文件
FirefoxProfileManager profileManager = new FirefoxProfileManager();
FirefoxProfile profile = profileManager.GetProfile("HARDDISKUSER");
IWebDriver driver = new FirefoxDriver(profile);
// 设置HTTP代理Firefox
FirefoxProfile firefoxProfile = new FirefoxProfile();
firefoxProfile.SetPreference("network.proxy.type", 1);
firefoxProfile.SetPreference("network.proxy.http", "myproxy.com");
firefoxProfile.SetPreference("network.proxy.http_port", 3239);
IWebDriver driver = new FirefoxDriver(firefoxProfile);
// 设置HTTP代理Chrome
ChromeOptions options = new ChromeOptions();
var proxy = new Proxy();
proxy.Kind = ProxyKind.Manual;
proxy.IsAutoDetect = false;
proxy.HttpProxy =
proxy.SslProxy = "127.0.0.1:3239";
options.Proxy = proxy;
options.AddArgument("ignore-certificate-errors");
IWebDriver driver = new ChromeDriver(options);
// 接受所有证书Firefox
FirefoxProfile firefoxProfile = new FirefoxProfile();
firefoxProfile.AcceptUntrustedCertificates = true;
firefoxProfile.AssumeUntrustedCertificateIssuer = false;
IWebDriver driver = new FirefoxDriver(firefoxProfile);
// 接受所有证书Chrome 
DesiredCapabilities capability = DesiredCapabilities.Chrome();
Environment.SetEnvironmentVariable("webdriver.chrome.driver", 
"C:\\PathToChromeDriver.exe");
capability.SetCapability(CapabilityType.AcceptSslCertificates, 
true);
IWebDriver driver = new RemoteWebDriver(capability);
// 设置Chrome选项.
ChromeOptions options = new ChromeOptions();
DesiredCapabilities dc = DesiredCapabilities.Chrome();
dc.SetCapability(ChromeOptions.Capability, options);
IWebDriver driver = new RemoteWebDriver(dc);
// 关闭JavaScript Firefox
FirefoxProfileManager profileManager = new FirefoxProfileManager();
FirefoxProfile profile = profileManager.GetProfile("HARDDISKUSER");
profile.SetPreference("javascript.enabled", false);
IWebDriver driver = new FirefoxDriver(profile);
// 设置默认页面加载超时
driver.Manage().Timeouts().SetPageLoadTimeout(new TimeSpan(10));
// 使用插件启动Firefox
FirefoxProfile profile = new FirefoxProfile();
profile.AddExtension(@"C:\extensionsLocation\extension.xpi");
IWebDriver driver = new FirefoxDriver(profile);
// 使用未打包的扩展启动Chrome
ChromeOptions options = new ChromeOptions();
options.AddArguments("load-extension=/pathTo/extension");
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.SetCapability(ChromeOptions.Capability, options);
DesiredCapabilities dc = DesiredCapabilities.Chrome();
dc.SetCapability(ChromeOptions.Capability, options);
IWebDriver driver = new RemoteWebDriver(dc);
//使用压缩扩展启动Chrome
ChromeOptions options = new ChromeOptions();
options.AddExtension(Path.GetFullPath("localpathto/extension.crx"));
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.SetCapability(ChromeOptions.Capability, options);
DesiredCapabilities dc = DesiredCapabilities.Chrome();
dc.SetCapability(ChromeOptions.Capability, options);
IWebDriver driver = new RemoteWebDriver(dc);
// 更改默认文件的保存位置
String downloadFolderPath = @"c:\temp\";
FirefoxProfile profile = new FirefoxProfile();
profile.SetPreference("browser.download.folderList", 2);
profile.SetPreference("browser.download.dir", downloadFolderPath);
profile.SetPreference("browser.download.manager.alertOnEXEOpen", 
false);
profile.SetPreference("browser.helperApps.neverAsk.saveToDisk", 
"application/msword, application/binary, application/ris, text/csv, 
image/png, application/pdf, text/html, text/plain, application/zip, 
application/x-zip, application/x-zip-compressed, 
application/download, application/octet-stream");
this.driver = new FirefoxDriver(profile);
相关推荐
敲敲敲-敲代码6 分钟前
游戏设计:推箱子【easyx图形界面/c语言】
c语言·开发语言·游戏
明月清风徐徐13 分钟前
Scrapy爬取豆瓣电影Top250排行榜
python·selenium·scrapy
ROC_bird..14 分钟前
STL - vector的使用和模拟实现
开发语言·c++
MavenTalk20 分钟前
Move开发语言在区块链的开发与应用
开发语言·python·rust·区块链·solidity·move
XiaoLeisj1 小时前
【JavaEE初阶 — 多线程】生产消费模型 & 阻塞队列
java·开发语言·java-ee
2401_840192271 小时前
python基础大杂烩
linux·开发语言·python
@东辰1 小时前
【golang-技巧】- 定时任务 - cron
开发语言·golang·cron
机器人天才一号1 小时前
C#从入门到放弃
开发语言·c#
吾与谁归in1 小时前
【C#设计模式(10)——装饰器模式(Decorator Pattern)】
设计模式·c#·装饰器模式
Mr_Xuhhh2 小时前
递归搜索与回溯算法
c语言·开发语言·c++·算法·github