C#中Selenium?WebDriver的常用操作小結(jié)
更新時(shí)間:2024年01月11日 11:29:40 作者:李建軍
這篇文章主要為大家詳細(xì)介紹了C#中Selenium?WebDriver的常用操作,文中的示例代碼講解詳細(xì),具有一定的借鑒價(jià)值,需要的小伙伴可以參考一下
初始化
//谷歌瀏覽器 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();
定位標(biāo)簽方法
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("http://*[@id='editor']"));
// 查找多個(gè)元素
IReadOnlyCollection<IWebElement> anchors =
this.driver.FindElements(By.TagName("a"));
//在另一個(gè)元素中搜索一個(gè)元素
var div = this.driver.FindElement(By.TagName("div"))
.FindElement(By.TagName("a"));
基本瀏覽器操作
// 導(dǎo)航到頁面
this.driver.Navigate().GoToUrl(@"http://google.com");
// 獲取頁面的標(biāo)題
string title = this.driver.Title;
// 獲取當(dāng)前URL
string url = this.driver.Url;
// 獲取當(dāng)前頁面的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;
高級(jí)元素操作
// 拖放
IWebElement element = driver.FindElement(
By.XPath("http://*[@id='project']/p[1]/div/div[2]"));
Actions move = new Actions(driver);
move.DragAndDropToOffset(element, 30, 0).Perform();
// 如何檢查元素是否可見
Assert.IsTrue(driver.FindElement(
By.XPath("http://*[@id='tve_editor']/div")).Displayed);
//上傳文件
IWebElement element =
driver.FindElement(By.Id("RadUpload1file0"));
String filePath =
@"D:\WebDriver.Series.Tests\\WebDriver.xml";
element.SendKeys(filePath);
// 滾動(dòng)焦點(diǎn)以控制
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("http://*[@id='tve_editor']/div"));
var cropArea = new Rectangle(element.Location,
element.Size);
var bitmap = bmpScreen.Clone(cropArea,
bmpScreen.PixelFormat);
bitmap.Save(fileName);
// 關(guān)注控件
IWebElement link =
driver.FindElement(By.PartialLinkText("Previous post"));
// 等待圖元的可見性
WebDriverWait wait = new WebDriverWait(driver,
TimeSpan.FromSeconds(30));
wait.Until(
ExpectedConditions.VisibilityOfAllElementsLocatedBy(
By.XPath("http://*[@id='tve_editor']/div[2]/div[2]/div/div")));
高級(jí)瀏覽器操作
// 處理JavaScript彈出窗口
IAlert a = driver.SwitchTo().Alert();
a.Accept();
a.Dismiss();
// 在瀏覽器窗口或選項(xiàng)卡之間切換
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);
// 切換到默認(rèn)文檔
this.driver.SwitchTo().DefaultContent();
高級(jí)瀏覽器配置
// Firefox配置文件
FirefoxProfileManager profileManager = new FirefoxProfileManager();
FirefoxProfile profile = profileManager.GetProfile("HARDDISKUSER");
IWebDriver driver = new FirefoxDriver(profile);
// 設(shè)置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);
// 設(shè)置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);
// 設(shè)置Chrome選項(xiàng).
ChromeOptions options = new ChromeOptions();
DesiredCapabilities dc = DesiredCapabilities.Chrome();
dc.SetCapability(ChromeOptions.Capability, options);
IWebDriver driver = new RemoteWebDriver(dc);
// 關(guān)閉JavaScript Firefox
FirefoxProfileManager profileManager = new FirefoxProfileManager();
FirefoxProfile profile = profileManager.GetProfile("HARDDISKUSER");
profile.SetPreference("javascript.enabled", false);
IWebDriver driver = new FirefoxDriver(profile);
// 設(shè)置默認(rèn)頁面加載超時(shí)
driver.Manage().Timeouts().SetPageLoadTimeout(new TimeSpan(10));
// 使用插件啟動(dòng)Firefox
FirefoxProfile profile = new FirefoxProfile();
profile.AddExtension(@"C:\extensionsLocation\extension.xpi");
IWebDriver driver = new FirefoxDriver(profile);
// 使用未打包的擴(kuò)展啟動(dòng)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);
//使用壓縮擴(kuò)展啟動(dòng)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);
// 更改默認(rèn)文件的保存位置
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的常用操作小結(jié)的詳細(xì)內(nèi)容,更多關(guān)于C# Selenium WebDriver的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
C#簡單實(shí)現(xiàn)發(fā)送socket字符串
這篇文章主要為大家詳細(xì)介紹了C#簡單實(shí)現(xiàn)socket字符串發(fā)送,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-09-09
.NET中的靜態(tài)與非靜態(tài)的區(qū)別分析
.NET中的靜態(tài)與非靜態(tài)的區(qū)別分析,需要的朋友可以參考一下2013-03-03
Unity計(jì)時(shí)器功能實(shí)現(xiàn)示例
計(jì)時(shí)器在很多地方都可以使用,本文主要介紹了Unity計(jì)時(shí)器功能實(shí)現(xiàn)示例,文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-10-10
unity3D實(shí)現(xiàn)三維物體跟隨鼠標(biāo)
這篇文章主要為大家詳細(xì)介紹了unity3D實(shí)現(xiàn)三維物體跟隨鼠標(biāo),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-12-12

