[Selenium With C#学习笔记] Lesson-02 Web元素定位
作者:Surpassme
来源:http://www.jianshu.com/p/cfd4ed1daabd
声明:本文为原创文章,如需转载请在文章页面明显位置给出原文链接,谢谢。
使用Selenium来做自动化测试,一般的流程是:查找定位元素--->操作元素--->断言,那么第一步我们需要能够完成查找并定位元素,Selenium目前提供了8种基本定位方法,可根据实际情况进行选择,如下示:
定位方法 |
示例 |
ID |
FindElement(By.Id("user")) |
Name |
FindElement(By.Name("username")) |
LinkText |
FindElement(By.LinkText("Login")) |
PartialLinkText |
FindElement(By.PartialLinkText("Next")) |
XPath |
FindElement(By.Xpath("//div[@id="login"]/input")) |
TagName |
FindElement(By.TagName("body")) |
ClassName |
FindElement(By.ClassName("table")) |
CSS |
FindElement(By.CssSelector("#login > input[type="text"]")) |
Step-1:启动浏览器
Selenium支持的浏览器较多,我拿目前三大使用较多的浏览器(IE、Chrome、Firefox)做一个示例,来演示如何启动三大浏览器,代码如下:
using System; using System.Collections.ObjectModel; //MS自带的单元测试框架 using Microsoft.VisualStudio.TestTools.UnitTesting; //Webdriver引用 using OpenQA.Selenium; //IE引用 using OpenQA.Selenium.IE; //Chrome引用 using OpenQA.Selenium.Chrome; //Firefox引用 using OpenQA.Selenium.Firefox; namespace SeleniumDemo { [TestClass] public class Lesson02 { //获取浏览器驱动程序路径 string driverPath = AppDomain.CurrentDomain.BaseDirectory; //定义浏览器类型枚举 public enum DriverType { IE, Chrome, Firefox }; //定义使用浏览器类型 DriverType dt = DriverType.Chrome; IWebDriver driver; //获取测试需要使用哪一种浏览器驱动 public IWebDriver GetDirverType(DriverType driverType) { switch (driverType) { case DriverType.IE: driver = new InternetExplorerDriver(driverPath); break; case DriverType.Chrome: driver = new ChromeDriver(); break; case DriverType.Firefox: //3.0之后的Selenium Webdriver才需要这样,2.0版本的可以直接以这种形式:driver = new FirefoxDriver(); FirefoxOptions fo = new FirefoxOptions(); //Firefox安装路径 fo.BrowserExecutableLocation = @"C:\Program Files\Mozilla Firefox\firefox.exe"; FirefoxDriverService fds = FirefoxDriverService.CreateDefaultService(driverPath); driver = new FirefoxDriver(fds, fo, TimeSpan.FromSeconds()); break; default: break; } return driver; } [TestMethod] public void Demo02() { driver = GetDirverType(dt); //访问百度 driver.Navigate().GoToUrl("https://www.baidu.com"); //查找搜索输入框,输入Selenium IWebElement searchText = driver.FindElement(By.Id("kw"));
//在输入前清空内容 searchText.Clear(); searchText.SendKeys("Selenium"); //查找元素 IWebElement searchBtn = driver.FindElement(By.Id("su")); //点击搜索按钮 searchBtn.Click(); //退出浏览器 driver.Quit(); //driver.Close(); } } }
Close()与Quit()区别:
driver.Close():在完成操作后,仅关闭浏览器窗口,不会关闭Webdriver会话(我们在测试每个用例时,都会启动一个浏览器驱动进程,如果使用Close()方法,则浏览器驱动进程不会关闭,则使用Quit()则会自动关闭)
driver.Quit():在完成操作后,同时关闭浏览器窗口和Weddriver会话
Step-2:使用8种基本定位方法
在介绍基本的8种定位方法前,我们可以看看使用各浏览器自带的Web开发工具或插件(Firebug/Firepath等)来查看如何进行元素查看和定位:
使用IE自带的Web开发工具(可使用F12快捷键进行操作)如下所示:
在Firefox中使用Firebug+Firepath进行定位元素,如下所示:
使用Chrome自带Web开发工具进行定位元素,如下所示:
在使用Selenium Webdriver进行元素定位时,通常使用FindElement或FindElements方法结合By类返回的元素句柄来定位元素。其中By类的常用定位方式共八种,现分别介绍如下:
- By.Id()
通过元素的id属性来定位元素,具有很强的唯一性,速度也较快。
Button: driver.FindElement(By.Id("submit_btn")).Click();
Link: driver.FindElement(By.Id("cancel_link")).Click();
Text: driver.FindElement(By.Id("username")).SendKeys("admin ") ;
HTML Div元素: driver.FindElement(By.Id("alert_div")).getText();
- By.Name()
通过元素的name属性来查找元素,在当前页面中可以不唯一,可能会存在同名的情况。
driver.FindElement(By.Name("comment")).SendKeys("comment ") ;
- By.LinkText()
通过文本链接来查找元素,该链接必须能在页面中为可见状态。在一些页面会出现在出现某个操作后,链接才能显示出来,如果没有上一步操作,是无法直接使用该方法进行定位元素的。
driver.FindElement(By.LinkText("新闻")).Click();
- By. PartialLinkText ()
PartialLinkText是对Link定位的一种补充,在文本链接比较长或文本链接动态生成的时候,可以使用该方法截取一部分文本进行定准。
driver.FindElement(By.PartialLinkText("新")).Click();;
- By. XPath ()
XPath 是一门在 XML 文档中查找信息的语言,可在 XML 文档中对元素和属性进行遍历。更多XPath信息可参考:http://www.w3school.com.cn/xpath/index.asp
driver.FindElement(By.XPath("//input[@id='kw']"));
- By.TagName()
该方法可通过元素的标签名称来定位查找元素,通常该方法能定位到的元素会存在一个或多个,建议结合FindElements()方法使用。
driver.FindElements(By.TagName("button"));
- By. ClassName ()
ClassName方法是通过元素的CSS样式表所引用的伪类名称来定位查找元素。通过情况下,一个元素会存在多个CSS样式值,如下所示:
<a href="https://www.baidu.com" class="btn btn-default">百度一下</a> <input type="submit" value="提交" class="btn btn-default btn-primary"/>
我们可以以下任何一种方法进行定位元素:
driver.FindElement(By.ClassName("btn-primary ")).Click(); //提交按钮
driver.FindElement(By.ClassName("btn ")).Click(); //百度一下链接
- By.CssSelector()
在CSS中,选择器是一种模式,用于选择需要添加样式的元素,更多资料可参考:http://www.w3school.com.cn/cssref/css_selectors.asp
driver.FindElement(By.CssSelector("#kw"));
- 多元素定位
通过FindElements可以一次返回多个匹配元素,使用方法与FindElement很像。示例如下:
ReadOnlyCollection<IWebElement> elements = driver.FindElements(By.ClassName("mnav"));
本文中需要使用到的浏览器驱动及插件可到百度网盘进行下载: https://pan.baidu.com/s/1kV6uzzx 密码:9m1q
本文完整代码如下:
using System;
using System.Collections.ObjectModel;
//MS自带的单元测试框架
using Microsoft.VisualStudio.TestTools.UnitTesting;
//Webdriver引用
using OpenQA.Selenium;
//IE引用
using OpenQA.Selenium.IE;
//Chrome引用
using OpenQA.Selenium.Chrome;
//Firefox引用
using OpenQA.Selenium.Firefox; namespace SeleniumDemo
{
[TestClass]
public class Lesson02
{
//获取浏览器驱动程序路径
string driverPath = AppDomain.CurrentDomain.BaseDirectory;
//定义浏览器类型枚举
public enum DriverType { IE, Chrome, Firefox };
//定义使用浏览器类型
DriverType dt = DriverType.Chrome;
IWebDriver driver;
//获取测试需要使用哪一种浏览器驱动
public IWebDriver GetDirverType(DriverType driverType)
{
switch (driverType)
{
case DriverType.IE:
driver = new InternetExplorerDriver(driverPath);
break;
case DriverType.Chrome:
driver = new ChromeDriver();
break;
case DriverType.Firefox:
//3.0之后的Selenium Webdriver才需要这样,2.0版本的可以直接以这种形式:driver = new FirefoxDriver();
FirefoxOptions fo = new FirefoxOptions();
//Firefox安装路径
fo.BrowserExecutableLocation = @"C:\Program Files\Mozilla Firefox\firefox.exe";
FirefoxDriverService fds = FirefoxDriverService.CreateDefaultService(driverPath);
driver = new FirefoxDriver(fds, fo, TimeSpan.FromSeconds());
break;
default:
break;
}
return driver;
} [TestMethod]
public void Demo02()
{
driver = GetDirverType(dt);
//访问百度
driver.Navigate().GoToUrl("https://www.baidu.com");
//查找搜索输入框,输入Selenium
IWebElement searchText = driver.FindElement(By.Id("kw"));
60 //在输入前清空内容
searchText.Clear();
searchText.SendKeys("Selenium");
//查找元素
IWebElement searchBtn = driver.FindElement(By.Id("su"));
//点击搜索按钮
searchBtn.Click();
//退出浏览器
driver.Quit();
//driver.Close();
} [TestMethod]
//一次定位多个元素
public void FindElementsDemo()
{
driver = GetDirverType(dt);
driver.Navigate().GoToUrl("https://www.baidu.com");
ReadOnlyCollection<IWebElement> elements = driver.FindElements(By.ClassName("mnav"));
Console.WriteLine("查找到的元素个数为:{0}", elements.Count);
for (int i = ; i < elements.Count; i++)
{
Console.WriteLine(elements[i].Text);
}
driver.Quit();
}
}
}
[Selenium With C#学习笔记] Lesson-02 Web元素定位的更多相关文章
- Selenium3+webdriver学习笔记2(常用元素定位方式,定位单个元素共8种,总共有23种)
#!/usr/bin/env python# -*- coding:utf-8 -*- from selenium import webdriver import time,os # about:ad ...
- selenium学习笔记(简单的元素定位)
收拾一下心情开始新的一周工作 继续是selenium的学习.配置成功后 由于所有操作都是建立在页面元素基础上的.所以下来就是学习定位元素 首先是基础的定位.就使用博客园首页搜索框为例: 下面是代码: ...
- Struts2 学习笔记 09 访问Web元素
我们想要访问Map类型request,session,application.真实类型HttpServletRequest,HttpSession,ServletContext的引用,并对它们进行操作 ...
- Solr 6.7学习笔记(02)-- 配置文件 managed-schema (schema.xml) -- 样例(6)
managed-schema 样例: <?xml version="1.0" encoding="UTF-8" ?> <!-- License ...
- ASP.NET MVC Web API 学习笔记---第一个Web API程序
http://www.cnblogs.com/qingyuan/archive/2012/10/12/2720824.html GetListAll /api/Contact GetListBySex ...
- udacity android 学习笔记: lesson 4 part b
udacity android 学习笔记: lesson 4 part b 作者:干货店打杂的 /titer1 /Archimedes 出处:https://code.csdn.net/titer1 ...
- Spring实战第八章学习笔记————使用Spring Web Flow
Spring实战第八章学习笔记----使用Spring Web Flow Spring Web Flow是一个Web框架,它适用于元素按规定流程运行的程序. 其实我们可以使用任何WEB框架写流程化的应 ...
- Spring实战第五章学习笔记————构建Spring Web应用程序
Spring实战第五章学习笔记----构建Spring Web应用程序 Spring MVC基于模型-视图-控制器(Model-View-Controller)模式实现,它能够构建像Spring框架那 ...
- Solr 6.7学习笔记(02)-- 配置文件 managed-schema (schema.xml)(3)
5. <fieldType> fieldType主要定义了一些字段类型,其name属性值用于前面<field>中的type属性的值.e.g. <fieldTyp ...
- Solr 6.7学习笔记(02)-- 配置文件 managed-schema (schema.xml) - filter(5)
自定义fieldType时,通常还会用到filter.filter必须跟在tokenizer或其它filter之后.如: <fieldType> <analyzer> < ...
随机推荐
- C++中的IO流
一,标准输入流 1.基本功能(头文件为iostream) char ch = cin.get();// 一次读取一个字符,如果遇到EOF则结束. cin.getline(buf,length);// ...
- numpy 安装
sudo apt-get install python-scipy sudo apt-get install python-numpy sudo apt-get install python-matp ...
- UIStackView属性解释
Distribution 分布: Fill:填充,会根据优先级来压缩或伸长元素 Fill Equal:全都相等,并且都填充满 Fill Proportionally:按比例填充,根据元素的内容多少的比 ...
- mysql常用博客论坛
大神博客: starive的博客:http://blog.itpub.net/26435490/viewspace-1133659/ 北在南方的博客:http://blog.itpub.net/226 ...
- andorid 开放工具集合
1.开放工具集合 http://www.androiddevtools.cn/
- onfocus在火狐、ie10浏览器失效解决方法方法
<script> function setit(){ if(document.all){ document.getElementById("myfr ...
- WMWARE下/sbin/scsi_id 返回值为空
[root@HE1 ~]# /sbin/scsi_id -g -u /dev/sdb 第一种是从VMWARE层面去解决,用文本编辑器修改vmx文件,在vmx文件中任意位置(通常在最后)添加如下行: d ...
- VAST3.0规范
VAST3.0视频广告投放规范 Posted on 2014年2月15日 1.术语 随着视频广告行业的发展,某些术语已经得到了广泛的采用.以下定义该文档中与视频广告投放相关的一些术语: 广告荚(Ad ...
- oracle求时间差的常用函数
oracle求时间差的常用函数 求时间差: 天: ROUND(TO_NUMBER(END_DATE - START_DATE)) 小时: ROUND(TO_NUMBER(END_D ...
- loadrunner:从数据库中取值进行参数化
下面我们介绍用数据库中的用户名来参数化登陆用户名. 框选住登陆名,点鼠标右键,弹出对话框,选择"替换为新参数"弹出对话框,此时参数名输入:name,参数类型选择File,如图 点& ...