Está en la página 1de 9

SELECTORES

Primero que todo, XPath (XML Path Language) es un lenguaje que


permite construir expresiones que recorren y procesan un documento
XML.
XPath permite buscar y seleccionar teniendo en cuenta la estructura
jerárquica del XML.
Tanto los selectores para XPath como para aplicarlos con css son muy
similares, ya que estos selectores se basan en la seleccion de etiquetas
y atributos de HTML/XML.
Lo primero que debemos aprender son las siguientes notaciones
o identificadores:

^ = Se utiliza cuando queremos referirnos a principio de un string.

$ =Se utiliza cuando nos referimos al final de un string.

* =Utilizado para referirnos a cualquier parte de un string.

La estructura general: <etiqueta>[atributo][identificador]=’Valor de


atributo’

Comencemos con los enlaces de descarga, o mejor aún con algun tipo de
archivo.
Tenemos el siguiente código:

<a href=“documento.pdf”>Enlace Descarga PDF</a>


<a href=“mailto:correo@mail.com”>Enlace de Correo Mailto</a>
<a href=“http://www.iguazoft.com/index.php”>Enlace a una URL</a>

Para referirnos a todos los enlaces que sean un link a una extension
cualquiera, en este caso un PDF, nuestra definición CSS quedaría de la
siguiente manera:

a[href $=’.pdf’]{
color:#F00;
}

Con un enlace que nos lleve a redactar un correo como lo es MAILTO:


a[href ^=’mailto:’]{
background:#FFC;
}
Con una URL que lleve el string iguazoft.com:
a[href *=’iguazoft.com’]{
border:#066 2px dotted;
}

Cabe resaltar que no solo sirve para los enlaces, sirve para parrafos, listas, o
cualquier etiqueta que podamos colocarle un atributo. digamos si tuviesemos
un parrafo con el atributo title tambien aplicaria de la siguiente manera:

<p title=”Idea Principal”>Contendido de Párrafo</p>

Referencia: http://blog.iguazoft.com/selectores-condicionales-en-css-y-xpath/

CSS
https://codigofacilito.com/articulos/selectores-de-css
Automation
https://www.neustar.biz/blog/inspecting-xpath-expressions-css-selectors-firefox-
chrome
This page describes some CSS rules and pseudo-classes that will help you
move your XPATH locators to CSS, a native approach on all browsers.

I: Simple
DIRECT CHILD

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

Examples:

//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:

//div//a

css=div a

ID

An element’s id in XPATH is defined using: “[@id='example']” and in CSS


using: “#”

Examples:

//div[@id='example']//a

css=div#example a

CLASS

For class, things are pretty similar in XPATH: “[@class='example']” while in


CSS it’s just “.”
Examples:

//div[@class='example']//a

css=div.example a

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.

</input> </input>
Let’s write a 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.

css=form input.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 without adding
a class.

</input> </input> </input> </input>


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

css=form input[name='username']
We can even chain filters to be more specific with our selections.

css=input[name='continue'][type='button']
Here Selenium will act on the input field with name=”continue” and
type=”button”

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.

 <p>Heading</p>
 Cat
 Dog
 Car
 Goat

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=ul#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=ul#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=ul#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 TE XT

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 700+
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://saucelabs.com/resources/articles/selenium-tips-css-selectors

https://support.smartbear.com/testcomplete/docs/app-testing/web/general/common-
tasks/finding-objects/css-selectors.html

Selenium WebDriver: Tools to identify


Locators easily

When automating a web application, the most important and time taking task is to
come up with unique locators for the elements present on the web page. Once you
find out the correct locator, the rest of the automation is relatively easier.
Finding correct and unique locators require human intelligence and below tools can
help you in a great deal when you start creating your scripts. Every automation
engineer should have these tools in their arsenal.

Cuando automatices una aplicación Web, lo más importante de las tareas es llegar a
localizadores únicos para los elementos presentes en la página web. Una vez que
encuentre el localizador correcto, el resto de la automatización es relativamente fácil.

Encontrar localizadores correctos y únicos requiere de la inteligencia humana y las


herramientas de debajo pueden ayudarte en gran medida cuando empieces a crear
tus scripts. Cada ingeniero de automatización debería tener estas herramientas en
su arsenal.
List of Tools to identify Locators
1.- Firebug (Firefox addon)
The favorite tool of web developers. Firebug integrates with Firefox to put a wealth
of web development tools at your fingertips while you browse. You can edit, debug,
and monitor CSS, HTML, and JavaScript live in any web page. Its console window
and inspection tool are the best available in the market.

La herramienta favorita de desarrolladores web. Firebug se integra con Firefox para


poner una gran cantidad de herramientas de desarrollo web a su alcance mientras
navega. Tú puedes editar, depurar y supervisar CSS, HTML y JavaScript de
cualquier página web.

2.- Firefinder for Firebug


This tool is simple, provide any XPath or CSS selector and it will highlight the
matching elements on the web. Simple, lightweight and easy to use. Install it on
top of Firebug.

Esta herramienta es simple, proporciona cualquier selector XPath o CSS y resaltará


los elementos coincidentes en la web. Sencillo, ligero y fácil de usar. Instálalo en la
parte superior de Firebug.

3.- FirePath for Firebug


Right Click on any element and select "Inspect in Firepath", this addon will generate
the XPath or CSS selector for you. It also highlights the element on the web page
and in the DOM. Very useful. Again install it on top of Firebug.

Haga clic derecho en cualquier elemento y seleccione "Inspect in Firepath", este


complemento generará el selector XPath o CSS para usted. También destaca el
elemento en la página web y el DOM. Muy útil. Una vez más instalarlo en la parte
superior de Firebug.

4.- WebDriver Element Locator (Firefox addon)


This addon will generate XPath for any given element. But the best thing is, it will
also generate WebDriver statements for you and also in the language of your
choice. Currently, it supports C#, Java, Python and Ruby. Just right-click on any
element and generate the code in your favorite language. It is that simple. The only
downside is that it only generates XPath.

Este complemento generará XPath para cualquier elemento dado. Pero lo mejor es
que también generará declaraciones de WebDriver para usted y también en el
idioma de su elección. Actualmente, soporta C #, Java, Python y Ruby.
Simplemente haga clic derecho en cualquier elemento y genere el código en su
idioma favorito. Es así de simple. El único inconveniente es que sólo genera XPath.

5.- Selector Detector (Bookmarklet)


Sometimes XPath and CSS Selectors do not work in a given situation. That's where
JQuery selector comes in handy. This is a bookmarklet created by Jessie A. Morris
and it will generate the jQuery selector for your on the clicked element. Go to this
link and drag the provided bookmarklet to your bookmarks bar. The button will
appear with the name Selector Detector. Now click on it and Click on any element
and it will generate the jQuery selector for you.

A veces, los selectores XPath y CSS no funcionan en una situación dada. Ahí es donde JQuery
selector viene muy bien. Este es un bookmarklet creado por Jessie A. Morris y generará el
selector jQuery para su elemento en el clic. Vaya a este enlace y arrastre el bookmarklet
proporcionado a su barra de marcadores. El botón aparecerá con el nombre Selector Detector.
Ahora haga clic en él y haga clic en cualquier elemento y generará el selector jQuery para
usted.

6.- SelectorGadget (Bookmarklet and Chrome Extension)


This tool is created by Andrew Cantino and Kyle Maxwell. It can generate CSS
Selectors for you. Authors describe the method to generate CSS selector like this.
Click on a page element that you would like your selector to match (it will turn
green). SelectorGadget will then generate a minimal CSS selector for that element,
and will highlight (yellow) everything that is matched by the selector. Now click on
a highlighted element to remove it from the selector (red), or click on an
unhighlighted element to add it to the selector. Through this process of selection
and rejection, SelectorGadget helps you come up with the Perfect CSS selector for
your needs.
See the video on the provided link to better understand this tool.

Esta herramienta es creada por Andrew Cantino y Kyle Maxwell. Puede generar selectores
CSS para usted. Los autores describen el método para generar selector CSS como este.

Haga clic en un elemento de página que desea que coincida con su selector (se volverá verde).
SelectorGadget generará entonces un selector CSS mínimo para ese elemento y resaltará
(amarillo) todo lo que coincida con el selector. Ahora haga clic en un elemento resaltado para
eliminarlo del selector (rojo), o haga clic en un elemento no resaltado para agregarlo al selector.
A través de este proceso de selección y rechazo, SelectorGadget le ayuda a encontrar el
selector CSS perfecto para sus necesidades.

Vea el video en el enlace proporcionado para entender mejor esta herramienta.

7.- SWD Page Recorder (.Net Application)


This is a comprehensive tool and it is more than just a generator. It is developed
by Dmitry Zhariy. Using this tool, you can generate selectors as well as full classes
for your code in Selenium WebDriver. It allows you to generate Page Object Models
for your automation code. If you are a C# developer, this tool will save you ample
amount of time. The best thing about this tool that you can write C# code in this
tool and see the live results on the browser. That is amazing.

Esta es una herramienta integral y es más que un generador. Es desarrollado por


Dmitry Zhariy. Usando esta herramienta, puede generar selectores, así como clases
completas para su código en Selenium WebDriver. Le permite generar Modelos de
objetos de página para su código de automatización. Si usted es un desarrollador
de C #, esta herramienta le ahorrará una amplia cantidad de tiempo. Lo mejor de
esta herramienta que puede escribir código C # en esta herramienta y ver los
resultados en vivo en el navegador. Esto es increíble.
Looking Glass (Java Application)
Although not as comprehensive as SWD Page Recorder, this tool is still useful in
finding elements. It also allows you to write groovy scripts and see the results live
on the browser. Good for Java developers.

Aunque no es tan completo como SWD Page Recorder, esta herramienta sigue
siendo útil para encontrar elementos. También le permite escribir scripts groovy y
ver los resultados en vivo en el navegador. Bueno para los desarrolladores de Java.

These were some of the tools to identify locators easily. I hope the above list helps
the automation engineers in saving their time to identify and verify element
locators. I am also working on an application inspired by Looking Glass and SWD
page recorder. It will allow you to verify your locators and generate C# classes for
you. I am calling it "SeleniumVerify". It is present on GitHub. Currently it is under
development and I will soon update you when it is ready for download.
Do you happen to know any other tools. Please share in comment and also give
your feedback on this article.

Estas fueron algunas de las herramientas para identificar localizadores fácilmente. Espero que
la lista anterior ayuda a los ingenieros de automatización a ahorrar tiempo para identificar y
verificar localizadores de elementos. También estoy trabajando en una aplicación inspirada en
Looking Glass y SWD. Le permitirá verificar sus localizadores y generar clases C # para usted.
Lo llamo "SeleniumVerify". Está presente en GitHub. Actualmente está en desarrollo y pronto lo
actualizaré cuando esté listo para su descarga.

¿Conoces alguna otra herramienta? Por favor, comparta en el comentario y también dar su
opinión sobre este artículo.

También podría gustarte