[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> < ...
随机推荐
- 原生JavaScript之“淘宝轮播图”
轮播图是我们学习原生js的必经之路 它包含很多基本知识的运用,像this的使用,DOM的操作,还有setInterval的使用和清除,浮动与定位等等,很好的考察了我们的基础知识牢不牢固, 话不多说,直 ...
- java8 泛型声明 The diamond operator ("<>") should be used
The diamond operator ("<>") should be used Java 7 introduced the diamond operator (& ...
- radioButton添加试题选项webview(二)
由于项目里radioGroup里,4个选项里加载的是webview,而不是radiobutton本身自己可设置的text类型,并且每个webview都需要和radiobutton对齐,所以这个布局有点 ...
- [Angular Tutorial] 5-Filtering Repeaters
在上一步中,我们花了很大功夫来布局应用的基础,所以我们现在做点简单点的吧!我们将会添加一个全文本搜索框(没错,这很简单). ·我们的应用现在会有一个搜索框,注意页面中手机列表的改变取决于用户在搜索框键 ...
- 如何获取DOM中当前获取焦点的元素
<script type="text/javascript"> function msg(e) // e = event { var target; //initial ...
- ceentos5.5 配置samba服务&用户&组
准备 Change Root Password passwd root 在提示下建立新密码 静态IP vi /etc/sysconfig/network-scripts/ifcfg-eth0 #网络 ...
- 遗传算法GA
遗传算法(Genetic Algorithms,GA)是一种全局优化方法,它借用了生物遗传学的观点,通过自然选择.遗传.变异等作用机制,实现种群中个体适应性的提高,体现了自然界中“物竞天择.适者生存” ...
- php常用图片处理类
<?php /** * 已知问题:1.在图片缩放功能中,使用imagecreatetruecolor函数创建画布,并使用透明处理算法,但PNG格式的图片无法透明.用imagecreate函数创建 ...
- Delphi 中的常用事件
OnActive 焦点称到窗体或控件时发生 OnClick 鼠标单击事件 OnDbClick 鼠标双击事件 OnClose和OnCloseQuery 当关闭一个窗体时就会响应OnClose和OnClo ...
- WPF 实现验证码功能
产生验证码的类:ValidCode.cs public class ValidCode { #region Private Fields /// <summary> /// PI /// ...