from https://saucelabs.com/resources/articles/selenium-tips-css-selectors
Sauce Labs uses cookies to give you the best online experience. If you continue to use this site, you agree to the use of cookies. Please see our privacy policy for details. Learn more
OK
TYPE KEYWORD SOLUTIONS
PLATFORMS
PRICING
RESOURCES
SUPPORT & SERVICES
COMPANY
CONTACT
FREE TRIAL
Selenium Tips: CSS Selectors
Posted June , by Sauce Labs
HOMERESOURCESARTICLESSELENIUM TIPS: CSS SELECTORS
This page describes some useful Selenium tips on CSS rules and pseudo-classes that will help you understand how to convert your XPATH locators to CSS, a native approach on all browsers. A CSS Selector is a combination of an element selector and a value which identifies the web element within a web page. They are string representations of HTML tags, attributes, Id and Class. As such they are patterns that match against elements in a tree and are one of several technologies that can be uses to select nodes in an XML document. I: Simple
DIRECT CHILD
A direct child in XPATH is defined by the use of a “/“, while on CSS, it’s defined using “>” Examples: XPath: //div/a CSS: div > a
CHILD OR SUBCHILD
If an element could be inside another or one it’s childs, it’s defined in XPATH using “//” and in CSS just by a whitespace. Examples: XPath: //div//a CSS: div a
ID
An element’s id in XPATH is defined using: “[@id='example']” and in CSS using: “#” - ID's must be unique within the DOM. Examples: XPath: //div[@id='example'] CSS: #example
CLASS
For classes, things are pretty similar in XPATH: “[@class='example']” while in CSS it’s just “.” Examples: XPath: //div[@class='example'] CSS: .example
II: Advanced
NEXT SIBLING
This is useful for navigating lists of elements, such as forms or ul items. The next sibling will tell selenium to find the next adjacent element on the page that’s inside the same parent. Let’s show an example using a form to select the field after username. <form class = "form-signin" role = "form" action = "/index.php" method = "post">
<h4 class = "form-signin-heading"></h4>
<input type = "text" class = "form-control" id = "username" name = "username" placeholder = "username" required autofocus></br>
<input type = "password" class = "form-control" id = "password" name = "password" placeholder = "password" required>
<p>
<button class = "btn btn-lg btn-primary btn-block radius" type = "submit" name = "login">Login</button>
</form>
Let’s write an XPath and css selector that will choose the input field after “username”. This will select the “alias” input, or will select a different element if the form is reordered. XPATH: //input[@id='username']/following-sibling::input[1]
CSS: #username + input
ATTRIBUTE VALUES
If you don’t care about the ordering of child elements, you can use an attribute selector in selenium to choose elements based on any attribute value. A good example would be choosing the ‘username’ element of the form above without adding a class. We can easily select the username element without adding a class or an id to the element. XPATH: //input[@name='username']
CSS: input[name='username']
We can even chain filters to be more specific with our selectors. XPATH: //input[@name='login'and @type='submit']
CSS: input[name='login'][type='submit']
Here Selenium will act on the input field with name="login" and type="submit" CHOOSING A SPECIFIC MATCH
CSS selectors in Selenium allow us to navigate lists with more finess that the above methods. If we have a ul and we want to select its fourth li element without regard to any other elements, we should use nth-child or nth-of-type. <ul id = "recordlist"> <li>Cat</li> <li>Dog</li> <li>Car</li> <li>Goat</li> </ul>
If we want to select the fourth li element (Goat) in this list, we can use the nth-of-type, which will find the fourth li in the list. CSS: #recordlist li:nth-of-type()
On the other hand, if we want to get the fourth element only if it is a li element, we can use a filtered nth-child which will select (Car) in this case. CSS: #recordlist li:nth-child()
Note, if you don’t specify a child type for nth-child it will allow you to select the fourth child without regard to type. This may be useful in testing css layout in selenium. CSS: #recordlist *:nth-child()
SUB-STRING MATCHES
CSS in Selenium has an interesting feature of allowing partial string matches using ^=, $=, or *=. I’ll define them, then show an example of each: ^= Match a prefix CSS: a[id^='id_prefix_']
A link with an “id” that starts with the text “id_prefix_” $= Match a suffix CSS: a[id$='_id_sufix']
A link with an “id” that ends with the text “_id_sufix” *= Match a substring CSS: a[id*='id_pattern']
A link with an “id” that contains the text “id_pattern” MATCHING BY INNER TEXT
And last, one of the more useful pseudo-classes, :contains() will match elements with the desired text block: CSS: a:contains('Log Out')
This will find the log out button on your page no matter where it’s located. This is by far my favorite CSS selector and I find it greatly simplifies a lot of my test code. Sauce Labs - Selenium Testing on the Cloud
Sauce Labs makes automated testing awesome. Our cloud-based platform helps developers test native & hybrid mobile and web applications across + browser / OS platforms, including iOS, Android & Mac OS X. Sauce supports Selenium, Appium and popular JavaScript unit testing frameworks, and integrates with all of the top programming languages, test frameworks and CI systems. With built-in video recording and screenshots of every test case, debugging tools, and secure tunneling for local or firewalled testing, Sauce makes running, debugging and scaling test suites quick and easy. Share this articleFacebookTwitterGoogle PlusLinkedIn
Free Trial
Get access to a free -day trial version, or contact Sales for more information. FREE TRIALCONTACT US
SOLUTIONS
Enterprise
Small Team
Open Source
PRODUCTS
Web Testing
Mobile App Testing
RESOURCES
Featured Resources
Blog
Why Us
SUPPORT
Contact Support
Knowledge Base
Documentation
Training
Status
COMPANY
Team
Values
Careers
Partners
Contact Us
NEWS
Press Releases
Press Coverage
Awards
COMMUNITY
Join Secret Sauce
Events
Appium
Selenium
JOIN OUR MAILING LIST
ENTER EMAIL ADDRESS
SUBMIT
FacebookTwitterGoogle PlusLinkedIn
© Sauce Labs. All rights reserved.Terms of ServicePrivacy Policy Contact us!Contact us!
We're not around, but we'd love to chat another time.
click here and type your Name
click here and type your Email
We're not around but we still want to hear from you! Leave us a note:
Send
Powered by Olark
Sauce Labs uses cookies to give you the best online experience. If you continue to use this site, you agree to the use of cookies. Please see our privacy policy for details. Learn more

Selenium Tips: CSS Selectors

Posted June 10, 2016 by Sauce Labs

This page describes some useful Selenium tips on CSS rules and pseudo-classes that will help you understand how to convert your XPATH locators to CSS, a native approach on all browsers.

A CSS Selector is a combination of an element selector and a value which identifies the web element within a web page.  They are string representations of HTML tags, attributes, Id and Class.  As such they are patterns that match against elements in a tree and are one of several technologies that can be uses to select nodes in an XML document.

I: Simple

DIRECT CHILD

A direct child in XPATH is defined by the use of a “/“, while on CSS, it’s defined using “>”

Examples:

XPath: //div/a

CSS: div > a

CHILD OR SUBCHILD

If an element could be inside another or one it’s childs, it’s defined in XPATH using “//” and in CSS just by a whitespace.

Examples:

XPath: //div//a

CSS: div a

ID

An element’s id in XPATH is defined using: “[@id='example']” and in CSS using: “#” - ID's must be unique within the DOM.

Examples:

XPath: //div[@id='example']

CSS: #example

CLASS

For classes, things are pretty similar in XPATH: “[@class='example']” while in CSS it’s just “.”

Examples:

XPath: //div[@class='example']

CSS: .example

II: Advanced

NEXT SIBLING

This is useful for navigating lists of elements, such as forms or ul items. The next sibling will tell selenium to find the next adjacent element on the page that’s inside the same parent. Let’s show an example using a form to select the field after username.

<form class = "form-signin" role = "form" action = "/index.php" method = "post">
<h4 class = "form-signin-heading"></h4>
<input type = "text" class = "form-control" id = "username" name = "username" placeholder = "username" required autofocus></br>
<input type = "password" class = "form-control" id = "password" name = "password" placeholder = "password" required>
<p>
<button class = "btn btn-lg btn-primary btn-block radius" type = "submit" name = "login">Login</button>
</form>

Let’s write an XPath and css selector that will choose the input field after “username”. This will select the “alias” input, or will select a different element if the form is reordered.

XPATH: //input[@id='username']/following-sibling::input[1]
CSS: #username + input

ATTRIBUTE VALUES

If you don’t care about the ordering of child elements, you can use an attribute selector in selenium to choose elements based on any attribute value. A good example would be choosing the ‘username’ element of the form above without adding a class.

We can easily select the username element without adding a class or an id to the element.

XPATH: //input[@name='username']
CSS: input[name='username']

We can even chain filters to be more specific with our selectors.

XPATH: //input[@name='login'and @type='submit']
CSS: input[name='login'][type='submit']

Here Selenium will act on the input field with name="login" and type="submit"

CHOOSING A SPECIFIC MATCH

CSS selectors in Selenium allow us to navigate lists with more finess that the above methods. If we have a ul and we want to select its fourth li element without regard to any other elements, we should use nth-child or nth-of-type.

<ul id = "recordlist">

<li>Cat</li>

<li>Dog</li>

<li>Car</li>

<li>Goat</li>

</ul>

If we want to select the fourth li element (Goat) in this list, we can use the nth-of-type, which will find the fourth li in the list.

CSS: #recordlist li:nth-of-type(4)

On the other hand, if we want to get the fourth element only if it is a li element, we can use a filtered nth-child which will select (Car) in this case.

CSS: #recordlist li:nth-child(4)

Note, if you don’t specify a child type for nth-child it will allow you to select the fourth child without regard to type. This may be useful in testing css layout in selenium.

CSS: #recordlist *:nth-child(4)

SUB-STRING MATCHES

CSS in Selenium has an interesting feature of allowing partial string matches using ^=, $=, or *=. I’ll define them, then show an example of each:

^= Match a prefix

CSS: a[id^='id_prefix_']

A link with an “id” that starts with the text “id_prefix_”

$= Match a suffix

CSS: a[id$='_id_sufix']

A link with an “id” that ends with the text “_id_sufix”

*= Match a substring

CSS: a[id*='id_pattern']

A link with an “id” that contains the text “id_pattern”

MATCHING BY INNER TEXT

And last, one of the more useful pseudo-classes, :contains() will match elements with the desired text block:

CSS: a:contains('Log Out')

This will find the log out button on your page no matter where it’s located. This is by far my favorite CSS selector and I find it greatly simplifies a lot of my test code.

Sauce Labs - Selenium Testing on the Cloud

Sauce Labs makes automated testing awesome. Our cloud-based platform helps developers test native & hybrid mobile and web applications across 900+ browser / OS platforms, including iOS, Android & Mac OS X. Sauce supports Selenium, Appium and popular JavaScript unit testing frameworks, and integrates with all of the top programming languages, test frameworks and CI systems. With built-in video recording and screenshots of every test case, debugging tools, and secure tunneling for local or firewalled testing, Sauce makes running, debugging and scaling test suites quick and easy.

 

css selectors tips的更多相关文章

  1. 转:SELENIUM TIPS: CSS SELECTORS

    This page will show you some CSS rules and pseudo-classes that will help you move your XPATH locator ...

  2. CSS:CSS使用Tips

    Css是前端开发中效果展现的主要部分之一,良好的Css书写习惯可以为实际的项目开发提高效率,也可以为实现良好的团队合作提供保证. 一般新手在使用Css的时候经常会犯一些错误,出现一些不经意的漏洞,如果 ...

  3. [css 揭秘]-css coding tips

    css 揭秘之css coding tips demo(1) html 代码: <body> <section> <div class="demo1" ...

  4. BeautifulSoup高级应用 之 CSS selectors /CSS 选择器

    BeautifulSoup支持最常用的CSS selectors,这是将字符串转化为Tag对象或者BeautifulSoup自身的.select()方法. 本篇所使用的html为: html_doc ...

  5. (3)选择元素——(4)css选择器(CSS selectors)

    The jQuery library supports nearly all of the selectors included in CSS specifications 1 through 3, ...

  6. CSS selectors for Selenium with example,selenium IDE

    CSS selectors for Selenium with example http://seleniumeasy.com/selenium-tutorials/css-selectors-tut ...

  7. [Selenium] 在Chrome的开发者工具中验证检查XPath/CSS selectors

    Evaluate and validate XPath/CSS selectors in Chrome Developer Tools Method 1 : From Elements panel U ...

  8. CSS Selectors

    CSS selectors are used to "find" (or select) HTML elements based on their element name, id ...

  9. Why are dashes preferred for CSS selectors / HTML attributes?

    Why are dashes preferred for CSS selectors / HTML attributes? I use dashes because I don't have to h ...

随机推荐

  1. Dubbo服务化框架使用整理

    一.垂直应用架构拆分 在应用架构的演进过程中,垂直应用架构因为开发便捷,学习成本低,对于实现业务功能的增删改查提供了高效的开发支持,有利于前期业务高速发展的的快速实现.但是随着系统业务功能的不断扩展和 ...

  2. ext3文件系统挂载优化--HBase

    1.设置noatime属性禁止记录文件访问时间戳以减少内核的管理开销 2.优化磁盘每个块为关键系统进程保留的固定空间:这个功能对关键磁盘比较有用, 比如操作系统依赖的磁盘,但这个功能对于数据存储来说几 ...

  3. vue.cli项目中src目录每个文件夹和文件的用法

    assets文件夹是放静态资源:components是放组件:router是定义路由相关的配置:view视图:app.vue是一个应用主组件:main.js是入口文件:

  4. scss是什么?在vue.cli中的安装使用步骤是?有哪几大特性?

    css的预编译: 使用步骤: 第一步:用npm下三个loader(sass-loader.css-loader.node-sass): 第二步:在build目录找到webpack.base.confi ...

  5. gitlab访问用户安装的postgresql数据库

    1.先将gitlab默认安装的postgresql的数据库中的数据,导入到用户安装的postgresql数据 用Navicat迁移数据.函数不用迁移. 2.配置gitlab对postgresql数据库 ...

  6. jmeter之最佳实践

    官方文档: http://jmeter.apache.org/usermanual/best-practices.html 翻译: 16.最佳实践 16.1 始终使用最新版本的JMeter JMete ...

  7. echart图表

    http://echarts.baidu.com/tutorial.html#5%20%E5%88%86%E9%92%9F%E4%B8%8A%E6%89%8B%20ECharts

  8. SSLServerSocket代码实现

    理解一个设计思想,结合代码是最好的途径.安全套接字服务端的实现代码如下: X509TrustManager MyX509TrustManager = new X509TrustManager() { ...

  9. jenkins借助winscp传本地文件到远程服务器上

    有这样的场景,我们的ftp上都是些重要的资料,所以大家基本只有可看的权限,只有部分管理人员有可读可写的权限,但是jenkins上基本使用的都是ftp的路径,这个时候就存在一些问题,某些开发需要将自己构 ...

  10. [LeetCode] 405. Convert a Number to Hexadecimal_Easy tag: Bit Manipulation

    Given an integer, write an algorithm to convert it to hexadecimal. For negative integer, two’s compl ...