C#中Selenium WebDriver的常用操作小结

 更新时间:2024年01月11日 11:29:40   作者:李建军  
这篇文章主要为大家详细介绍了C#中Selenium WebDriver的常用操作,文中的示例代码讲解详细,具有一定的借鉴价值,需要的小伙伴可以参考一下

初始化

//谷歌浏览器
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();

定位标签方法

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"));
基本浏览器操作
// 导航到页面
this.driver.Navigate().GoToUrl(@"http://google.com");
// 获取页面的标题
string title = this.driver.Title;
// 获取当前URL
string url = this.driver.Url;
// 获取当前页面的HTML源
string html = this.driver.PageSource;

基本要素操作

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;

高级元素操作

// 拖放
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")));

高级浏览器操作

// 处理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();

高级浏览器配置

// 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);

以上就是C#中Selenium WebDriver的常用操作小结的详细内容,更多关于C# Selenium WebDriver的资料请关注脚本之家其它相关文章!

相关文章

  • Unity之Luaframework框架lua调用C#方法

    Unity之Luaframework框架lua调用C#方法

    这篇文章主要介绍了Unity之Luaframework框架lua调用C#方法,在这里需要写一个C#脚本,脚本里写方法需要在lua中调用,具体实例代码参考下本文吧
    2021-09-09
  • C#通过cmd调用7z软件实现压缩和解压文件

    C#通过cmd调用7z软件实现压缩和解压文件

    这篇文章介绍了C#通过cmd调用7z软件实现压缩和解压文件的方法,文中通过示例代码介绍的非常详细。对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2022-04-04
  • C#中判断字符串是全角还是半角的实现代码

    C#中判断字符串是全角还是半角的实现代码

    本篇文章主要是对C#中判断字符串是全角还是半角的实现代码进行了介绍,需要的朋友可以过来参考下,希望对大家有所帮助
    2014-01-01
  • 详解C#如何实现分割视频

    详解C#如何实现分割视频

    这篇文章主要为大家详细介绍了C#如何实现将视频文件分割成一帧帧图片的方法,文中的示例代码讲解详细,对我们学习C#有一定的帮助,感兴趣的小伙伴可以跟随小编一起了解一下
    2022-12-12
  • C#制作简单的多人在线即时交流聊天室

    C#制作简单的多人在线即时交流聊天室

    这篇文章主要介绍了C#制作简单的多人在线即时交流聊天室的相关资料,需要的朋友可以参考下
    2015-11-11
  • C# Linq读取XML文件的实例

    C# Linq读取XML文件的实例

    C# Linq读取XML文件的实例,需要的朋友可以参考一下
    2013-05-05
  • c#代码自动修改解决方案下任意文件实例

    c#代码自动修改解决方案下任意文件实例

    这篇文章主要介绍了c#代码自动修改解决方案下任意文件实例,有需要的朋友可以参考一下
    2013-11-11
  • c#实现图片二值化例子(黑白效果)

    c#实现图片二值化例子(黑白效果)

    这篇文章主要介绍了c#实现图片二值化例子,图像二值化就是将图像上的像素点的灰度值设置为0或255,也就是将整个图像呈现出明显的黑白效果,需要的朋友可以参考下
    2014-08-08
  • C#实现文本转语音功能

    C#实现文本转语音功能

    这篇文章主要为大家详细介绍了C#实现文本转语音功能,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2022-03-03
  • C# OpenCvSharp实现图片批量改名

    C# OpenCvSharp实现图片批量改名

    这篇文章主要为大家详细介绍了C#如何结合OpenCvSharp实现图片批量改名功能,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下
    2024-03-03

最新评论