[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> < ...
随机推荐
- Word中的公式向上偏或向下偏的解决方法
在word 2010中,发现公式无法与文字排成一行时,可选中文字,然后点“字体”,然后“高级”选项中选择“位置”,然后根据不同情况选择“标准”.“提升”.“降低”.
- 每个Javascript开发者都应当知道的那些事
每个Javascript开发者都应当知道的那些事 2015-06-07 前端大全 (点击上方蓝字,可快速关注我们) Javascript是一种日益增长的语言,特别是现在ECMAScript规范按照每年 ...
- Ubuntu安装飞鸽传输
飞鸽传书下载地址 http://www.ipmsg.org.cn/ipmsg/download.html 下载以后解压压缩包,会有一个可执行文件,executable文件. ./Qipmsg 如果没报 ...
- Antx简介(ali_PPT)
Antx的由来: §最早,我们用Makefile来build系统 •Makefile不适合Java的编译 §后来,我们用Ant来build系统 •开始时很不错 •随着项目增多,出现困难 §利用bean ...
- 在Delphi中隐藏程序进程
在开发某些软件的时候,为了保护程序自身,就需要用到隐藏程序进程.以下通过实例来讲解隐藏程序进程的方法: 1.创建一个新的项目 Project1 选择File,New Application.在表单Fo ...
- Extjs换肤+cookie皮肤记忆功能
http://www.myext.cn/kaifa/a_102.html Ext之家 <title>无标题页</title> <link rel=" ...
- 修改GitHub上项目语言显示的问题
问题 最近将自己写的博客放到github上了.由于使用了富文本编辑器.jQuery.Bootstrap等第三方插件,导致js.css等代码远远超过你自己写的代码. 于是也就成这样了 而且这里也显示Ja ...
- loadrunner:web services接口测试
本文以实例讲解web services接口测试操作,内容包括:脚本生成.参数化和接口与接口间的取值关联操作. 网站"http://www.webxml.com.cn/zh_cn/web_se ...
- HDU1173
采矿 Time Limit: 10000/5000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submiss ...
- Redis系列三(redis配置文件分析)
在第一篇文章中有提到过redis.conf这个文件,这个文件就是redis-server的具体配置了.要使用好redis,一定要搞清楚redis的配置文件,这样才能最大的发挥redis的性能. # B ...