[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> < ...
随机推荐
- jsoup的介绍使用(转)
jsoup文档: http://www.open-open.com/jsoup/ 原链接: http://www.oschina.net/question/12_14127 jsoup 简介 Java ...
- PHP上传文件大小的修改
采用了plupload来上传文件,但是一直失败. 设置了插件的参数和接受的参数,仍旧失败. 此时想到php.ini中需要修改 post_max_sizeupload_file_size 然后重启服务器
- java和Ajax
原博(实在太啰嗦了):https://netbeans.org/kb/docs/web/ajax-quickstart_zh_CN.html 1.Ajax的基本原理 Ajax 代表异步 JavaScr ...
- jquery ajax promise
$request = $.getJSON('test.php'); $request.done(process1); $request.done(process2); $request.always( ...
- jquery proxy
slice = Array.prototype.slice,// Bind a function to a context, optionally partially applying any // ...
- Cassandra 单机入门例子——有索引
入门例子: http://wiki.apache.org/cassandra/GettingStarted 添加环境变量并source生效,使得可以在任意位置执行cassandra/bin安装目录下的 ...
- Hibernate懒加载的三种解决方案
Hibernate懒加载的两种解决方案: 1.Hibernate.initialize(代理对象) 2.在*.hbm.xml映射文件中添加lazy="false"属性 3.使用op ...
- Java 英语
Open quote,左括弧 associated with,关联
- Collections.sort的两种用法
http://gwh-08.iteye.com/blog/1233401/ class Foo implements Comparable<Foo>{ @Override public i ...
- RIP 相对寻址
知识共享许可协议本作品采用知识共享署名 4.0 国际许可协议进行许可.转载保留声明头部与原文链接https://luzeshu.com/blog/rip-relative-addressing 本博客 ...