//点击按钮/链接click()
Driver.FindElement(By.XPath("//input[@id='submit' and @value='下一步']")).click();
8:Selenium中等待页面上的元素加载完成
//等待页面元素加载完成
//默认等待100秒
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(100));
//等待页面上ID属性值为submitButton的元素加载完成
wait.Until((d) => { return WaitForObject(By.Id("submitButton")); });
9:Selenium中模拟鼠标晃动
//模拟光标晃动movebyoffset()
Actions action = new Actions(driver);
action.MoveByOffset(2, 4);
10:Selenium中对iframe中元素的定位
5.1:切换焦点到id为固定值的iframe上
进入页面后,光标默认焦点在DefaultContent中,若想要定位到iframe 需要转换焦点
driver.SwitchTo().DefaultContent();
//切换焦点到mainFrame
driver.SwitchTo().Frame("mainFrame");
需要注意的是:切换焦点之后若想切换焦点到其他iframe上 需要先返回到defaultcontent,再切换焦点到指定的iframe上。
5.2切换焦点到id值为动态值的iframe上
有时候 页面上浮出层的id为动态值,此时需要先获取所有符合记录的iframe放置在数组中,然后遍历数组切换焦点到目标iframe上。
如下方法:
protected string bizFrameId = string.Empty;
protected string bizId = string.Empty;
//获取动态iframe的id值
protected void SetIframeId()
{
ReadOnlyCollection<IWebElement> els = driver.FindElements(By.TagName("iframe"));
foreach (var e in driver.FindElements(By.TagName("iframe")))
{
string s1 = e.GetAttribute("id");
if (s1.IndexOf("window") >= 0 && s1.IndexOf("content") >= 0)
{
bizFrameId = e.GetAttribute("id");
string[] ss = s1.Split(new char[] { '_' });
bizId = ss[1];
}
}
}
11:Selenium中关闭多个子Browser窗口
//获取所有的WindowHandle,关闭所有子窗口
string oldwin = driver.CurrentWindowHandle;
ReadOnlyCollection<string> windows = driver.WindowHandles;
foreach (var win in windows)
{
if (win != oldwin)
{
driver.SwitchTo().Window(win).Close();
}
}
driver.SwitchTo().Window(oldwin);
12:Selenium中对下拉框的操作
//选择下拉框
protected void SelectUsage(string selectid, string text)
{
IWebElement select = Find(By.Id(selectid));
IList<IWebElement> AllOptions = select.FindElements(By.TagName("option"));
foreach (IWebElement option in select.FindElements(By.TagName("option")))
{
if (option.GetAttribute("value").Equals(text))
option.Click();
}
}
13:Selenium中对confirm ,alert ,prompt的操作
//在本次浏览器兼容性测试项目中遇到的只有confirm和alert
//下面举例说明confirm和alert的代码,prompt类似
//confirm的操作
IAlert confirm = driver.SwitchTo().Alert();
confirm.Accept();
//Alert的操作
//个人网银中同样的业务有时候不会弹对alert,此时需要判断alert是否存在
//对Alert提示框作确定操作,默认等待50毫秒
protected void AlertAccept()
{
AlertAccept(0.05);
}
//等待几秒,可以为小数,单位为秒
protected void AlertAccept(double waitseSonds)
{
double nsleepMillon = waitseSonds * 1000;
int k=0;
int split=50;
IAlert alert = null;
do
{
k++;
Thread.Sleep(split);
alert = driver.SwitchTo().Alert();
} while (k * split <= nsleepMillon || alert==null);
if (alert != null)
{
alert.Accept();
}
}
14:Selenium WebDriver的截图功能
//WebDriver中自带截图功能
Screenshot screenShotFile = ((ITakesScreenshot)driver).GetScreenshot();
screenShotFile.SaveAsFile("test",ImageFormat.Jpeg);