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 10, 2016 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(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. 

Share this articleFacebookTwitterGoogle PlusLinkedIn
Free Trial
Get access to a free 14-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
? 2018 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

OK

SOLUTIONS

PLATFORMS

PRICING

RESOURCES

SUPPORT & SERVICES

COMPANY

CONTACT

FREE TRIAL

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.

原文地址:https://www.cnblogs.com/bamboozone/p/10427171.html

时间: 2024-10-29 05:28:41

https://saucelabs.com/resources/articles/selenium-tips-css-selectors的相关文章

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

Evaluate and validate XPath/CSS selectors in Chrome Developer Tools Method 1 : From Elements panel Use the search function inside Elements panel to evaluate XPath/CSS selectors and highlight matching nodes in the DOM. 1.Press F12 to open up Chrome De

盘点 CSS Selectors Level 4 中新增的选择器

CSS 选择器在实践中是非常常用的,无论是在写样式上或是在 JS 中选择 DOM 元素都需要用到.在 CSS Selectors Level 4 中,工作组继续为选择器标准添加了更丰富的选择器.下面我们来了解一下. :is() :is 是一个用于匹配任意元素的伪类,使用方法很简单,只需要将选择器列表传入即可,也就是说,:is()的结果也就是传入的选择器列表中选中的元素. 那么这个选择器有什么用呢?举个例子:我需要对不同层级下的h1标签设置不同的字体大小: /* Level 0 */ h1 { f

CSS Selectors

Table of Contents Universal Selector Element Selector Class Selector ID Selector Attribute Selector Attribute Equals Attribute Begins With Attribute Begins With Language Code Attribute Ends With Attribute Contains Attribute Contains Word Group Select

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

BeautifulSoup支持最常用的CSS selectors,这是将字符串转化为Tag对象或者BeautifulSoup自身的.select()方法. 本篇所使用的html为: html_doc = """<html><head><title>The Dormouse's story</title></head><body><p class="title"><b&

selenium之css定位

实在记不住,烂笔头就记一下吧. 一. 单一属性定位 1:type selector driver.find_element_by_css_selector('input') 2:id 定位 driver.find_element_by_css_selector('#kw') 3:class 定位 driver.find_element_by_css_selector('.s_ipt') 4:其他属性定位 driver.find_element_by_css_selector('[name='wd

Selenium IDE CSS元素选择器

点击链接加入群[悦分享测试联盟]:https://jq.qq.com/?_wv=1027&k=5FiMKHH Css选择器 通过节点属性查找 .class                 选择 class="intro"的所有元素. #id                     选择 id="firstname"的所有元素. *                         选择所有元素. 通过节点关系查找 element element        

Selenium之Css Selector使用方法

什么是Css Selector? Css Selector定位实际就是HTML的Css选择器的标签定位 工具 Css Selector的练习建议使用火狐浏览器,下载插件,FireFinder.FireBug.Firepath结合使用. Css Selector的使用方法 1.Css Selector支持ID.Class的定位,与HTML中CSS定位相同 2.Css Selector支持标签定位,但是用处不大 3.Css Selector支持任意属性定位 4.Css Selector支持标签属性组

Selenium定位—CSS

CSS定位 浏览器检查元素定位方法 示例:https://www.12306.cn/index/index.html 定位,出发地输入框元素 在Console输入 $$() ,括号中填写CSS定位语句 查询结果显示为1条 如图:输入 $$("#fromStationText")  ,点击回车,即可显示查询结果 鼠标放在查询结果 0:  上面,则会在web界面上高亮显示该位置 鼠标点击查询结果 0:  ,则会跳到 Elements 界面,并高亮显示定位的元素 查询结果显示为多条 如图:输

selenium tips

1.利用selenium的webdriver驱动浏览器.(可以获取浏览器cookie) 2.selenium之WebDriver . 3.Selenium+Phantomjs数据抓取环境配置 . *** walker * 2-14-12-26 ***