C#Selenium常用语法功能

环境搭建:http://www.cnblogs.com/NorthAlan/p/5155915.html

初始化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.Title     //获取网页标题

                           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

猜你喜欢

转载自blog.csdn.net/a1003434346/article/details/80257946