发布:2021/2/19 17:26:01作者:管理员 来源:本站 浏览次数:1081
环境搭建:http://www.cnblogs.com/NorthAlan/p/5155915.html
在项目名\引用\右击\管理NuGet程序包\搜索Selenium\安装以下:
Selenium.WebDriver
Selenium.Support
可选:
Selenium.Firefox.WebDriver //火狐浏览器驱动
Selenium.Chrome.WebDriver //谷歌浏览器驱动
初始化google浏览器时可能会出错,好像要google浏览器的驱动还是版本不对应,建议用火狐作自动化测试
初始化:
IWebDriver driver = new FirefoxDriver(); //会打开浏览器
driver.Navigate().GoToUrl(@"url"); //到指定网址
//设置隐性等待时间(没有找到元素一直找,直到指定时间超时(单位是秒),对当前对象全局生效)
driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(10);
driver.FindElement(By.Id("txtUserName")).SendKeys(UserName); //给元素写入内容
driver.FindElement(By.Id("btnLogin")).Click(); //给元素单击事件
//获取Cookie
String Cookie = String.Empty;
ICookieJar listCookie = driver.Manage().Cookies;
for (int i = 0; i < listCookie.AllCookies.Count; i++)
{
Cookie += listCookie.AllCookies[i].Name + "=" + listCookie.AllCookies[i].Value + ";";
}
//给分组框设置当前选项
SelectElement select = new SelectElement(driver.FindElement(By.Id("selectIndustry1")));
//设置1级分类
select.SelectByIndex(int index);
也可以用js(Jquery)给分组框设置元素:
((IJavaScriptExecutor)driver).ExecuteScript("document.getElementById('prov').value='时尚饰品';");
常用获取元素方法:
//通过class获取元素
By.ClassName("fbcpn_form_l"))
//通过ID获取元素
By.Id("fbcpn_form_l"))
//通过Xpath获取元素
By.XPath("//*[@id='span_IndustryColumn']/div[1]"]/div[1]/input[1]");
Xpath里用class元素查找方式是//*[@class='clearfix']/li[1]/a[1]/img[1]"
//模糊匹配,contains为属性关键词,keyword为模糊字符串
driver.FindElement(By.XPath("//input[contains(@name, 'keyword')]"));
//通过纯文本信息查找
driver.FindElement(By.XPath("//*[text()='管理信息/发布信息']")).Click();
//利用js设置网页元素的属性
//设置删除为显示
String js = "document.getElementsByClassName('delete')[5].style.display='block';";
((IJavaScriptExecutor)driver).ExecuteScript(js);
//信息框操作
IAlert alert = driver.SwitchTo().Alert(); //转到弹出框
String alertInfoText = alert.Text; //获取弹出框信息提示
//点击确定按钮
alert.Accept();
driver.SwitchTo().Frame(0); //转到弹出框架页面
driver.SwitchTo().ParentFrame(); //返回框架页面
//获取旧窗口句柄
var oldWinHandle = webDriver.CurrentWindowHandle;
//对新页面进行操作,转到新页面,下标从0开始,1代表第二个页面
webDriver.SwitchTo().Window(webDriver.WindowHandles[1]);
webDriver.Close(); //关闭当前句柄页面
//获取一共有几个页面
webDriver.WindowHandles.Count
//返回页面
webDriver.SwitchTo().Window(webDriver.WindowHandles[0]);
webDriver.Title //获取网页标题
//关闭当前页面
webDriver.Close();
webDriver.Quit(); //关闭网页
//对某个元素右键
Actions actions = new Actions(driver);
actions.ContextClick(driver.FindElement(By.Name("validateCode"))).Perform();
判断元素是否存在:
IWebElement webElement = driver.FindElement(By.XPath("//*[@id='fileUp']/tbody[1]/tr[2]/td[1]/input[1]"));
webElement.Displayed
© Copyright 2014 - 2025 柏港建站平台 ejk5.com. 渝ICP备16000791号-4