Test XPath Css Selector Example

Selenium Tips: CSS Selectors

Learn about CSS rules and pseudo-classes to help you move your XPATH locators to CSS.

In order for Selenium or Appium to click on an element, type into it, or mouse in or out, the tool first needs to find the element. The WebDriver code library provides methods to do just that, such as findelement() or findelements(). These usually take a locator, which can be created by ID, XPATH Code, or Cascading Style Sheets (CSS). Getting the XPATH code can be as easy as selecting the element in developer tools or using something like Chropath. Fundamentally, XPATH is a query language for XML-like documents, such as web pages. It can be awkward to write, brittle, and even more awkward to reverse engineer. As a result, CSS has gained favor as the way to identify objects in WebDriver.

Читайте также:  What are data objects in java

Like most powerful things, CSS has a bit of a learning curve. It’s certainly a lot more challenging than cutting and pasting from a tool. Yet if you invest the time in learning CSS Selectors, you can have more powerful bindings that are easier to read, less brittle, and slightly more closely integrated into the browser platform.

Today we’ll provide CSS rules, tips, and pseudo-classes to either get you out on the right foot, or, perhaps help you move your XPATH locators to CSS.

Getting Started with CSS Selectors

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 used to select nodes in an XML document.

Today we’ll cover simple CSS selectors, then more advanced, then pseudo-classes, which are essentially powerful, built-in matching functions that reduce a search to just what you are looking for.

I: Simple

Id

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

Источник

Selenium XPath Css Selector Example

In selenium, you can use id, name as a locator to find Web Elements accurately. But in some cases, the id is generated dynamically and the name is also not provided. So XPath and CSS selectors are the most efficient way to locate web elements in such scenarios. We will show you examples of using XPath and CSS selectors to find web elements in this article.

1. This Example Will Use The Below Html File Content.

 .btnBackground < background-color : red; >.btnFont  
UserName :
Password :
Email1 : [email protected]"/>
Email2 : [email protected]" style="background-color: red"/>

Forget Password Register

xpath-css-selector-example-page

  • Below is the above Html web page in a web browser.
  • There are the following web elements in the above Html form.
  • Username and password have id and name with different values.
  • Two email input text box has the same name but different value. And the email label is wrapped by an Html span tag.
  • The Submit button has id, value, and style attributes.
  • The Reset button has id, value, and class attributes.
  • Two links for “Forget Password” and “Register“.
  • 2. Locate Web Element By XPath Example.

    1. By id : //*[@id=»userName»] .
    2. By name : //input[@name=»passwd»] . If there has two input text boxes with the same name “email” as the example code, we can use //*[@name=’email’][1] , the index starts from 1.
    3. By name and value : //input[@name=’email’][@value='[email protected]’] .
    4. By CSS style value : //input[@name=’email’][@style=’background-color: red’] .
    5. By complete match text : //span[.=’Email1′] .
    6. By partial match text : //*[contains(text(),’Email’)] .
    7. Case insensitive xpath use translate(): //*[contains(translate(text(), ‘ABCDEFGHIJKLMNOPQRSTUVWXYZ’, ‘abcdefghijklmnopqrstuvwxyz’), ‘EMaIl’)]
    8. By Html a tag href attribute: //a[@href=’forgetPassword.html’] .
    9. Click here to learn more about XPath functions.

    3. Locale Web Element By CSS Example.

    1. CSS is the abbreviation of “Cascading Style Sheet“. It is used in Html to make web element’s layout and style beautifully.
    2. CSS selector is a path pattern that can use a web element’s CSS attribute to locate a web element in the web page.
    3. CSS selector is simpler and faster than XPath, especially in Internet Explorer.
    4. Syntax : tagName[attributename=attributeValue] .
    5. A dot (.) is used to refer to CSS class : input.btnBackground.btnFont .
    6. Hash(#) is used to refer to id : input#userName .
    7. By id : input[id=userName] .
    8. By name : input[name=passwd] .
    9. Get web element list with same name element : input[name=email] .
    10. By name and value : input[name=email][value='[email protected]’] .
    11. By CSS style : input[name=email][style=’background-color: red’] .
    12. By Html a tag href attribute: a[href=’forgetPassword.html’] .
    13. ‘^’ means the start of the string : input[name^=’em’] .
    14. ‘$’ means the end of the string : input[name$=’il’] .
    15. ‘*’ means contain the string : input[name*=’ai’] .
    16. Use child node selector : form>input[name*=’ai’] .
    17. Use “+” to locate two or more adjacent web elements: input#submitBtn+input[id=’resetBtn’] .

    4. Find Web Elements By XPath & CSS Selectors With WebDriver Example Java Code.

    public class TestXPathCssSelector < public static void main(String[] args) < WebDriver driver = new FirefoxDriver(); driver.get("file://C:/WorkSpace/dev2qa.com/Code/src/com/dev2qa/webdriver/TestXPathCssSelector.html"); ListlocatorList = new ArrayList(); By byUserNameId = By.xpath("//input[@id='userName']"); locatorList.add(byUserNameId); By byPasswordName = By.xpath("//input[@name='passwd']"); locatorList.add(byPasswordName); By byEmail1 = By.xpath("//*[@name='email'][1]"); locatorList.add(byEmail1); By byEmailNameAndValue = By.xpath("//input[@name='email'][@value='[email protected]']"); locatorList.add(byEmailNameAndValue); By byEmailNameAndStyle = By.xpath("//input[@name='email'][@style='background-color: red']"); locatorList.add(byEmailNameAndStyle); By byTextComplete = By.xpath("//span[.='Email1']"); locatorList.add(byTextComplete); By byTextPartial = By.xpath("//*[contains(text(),'Email')]"); locatorList.add(byTextPartial); By byForgetPasswordHref = By.xpath("//a[@href='forgetPassword.html']"); locatorList.add(byForgetPasswordHref); //Below are css selector example. By byCssResetClass = By.cssSelector("input.btnBackground.btnFont"); locatorList.add(byCssResetClass); By byCssUserNameHashId = By.cssSelector("input#userName"); locatorList.add(byCssUserNameHashId); By byCssUserNameId = By.cssSelector("input[id=userName]"); locatorList.add(byCssUserNameId); By byCssPasswordName = By.cssSelector("input[name=passwd]"); locatorList.add(byCssPasswordName); By byCssEmail = By.cssSelector("input[name=email]"); locatorList.add(byCssEmail); By byCssEmailNameAndValue = By.cssSelector("input[name=email][value='[email protected]']"); locatorList.add(byCssEmailNameAndValue); By byCssEmailNameAndStyle = By.cssSelector("input[name=email][style='background-color: red']"); locatorList.add(byCssEmailNameAndStyle); By byCssForgetPasswordHref = By.cssSelector("a[href='forgetPassword.html']"); locatorList.add(byCssForgetPasswordHref); By byCssEmailStartStr = By.cssSelector("input[name^='em']"); locatorList.add(byCssEmailStartStr); By byCssEmailEndStr = By.cssSelector("input[name$='il']"); locatorList.add(byCssEmailEndStr); By byCssEmailContainStr = By.cssSelector("input[name*='ai']"); locatorList.add(byCssEmailContainStr); By byCssEmailUseChildSelector = By.cssSelector("form>input[name*='ai']"); locatorList.add(byCssEmailUseChildSelector); By byCssEmailUseaAjacentlector = By.cssSelector("input#submitBtn+input[id='resetBtn']"); locatorList.add(byCssEmailUseaAjacentlector); for(By locator : locatorList) < TestXPathCssSelector.findElement(driver, locator); >driver.quit(); > private static void findElement(WebDriver driver, By locator) < ListeleList = driver.findElements(locator); int size = eleList.size(); if(size>0) < System.out.println("There has " + size +" web element located by " + locator.toString() + " exist."); >else < System.out.println("Web element located by " + locator.toString() + " do not exist."); >> >

    Источник

    How to Write the Best XPATH and CSS Selectors for Your Web Scraper

    Selectors are one of the most important pieces of your scraper. Well-written selectors make your web scraper work efficiently and fast. When the website’s layout changes your scraper’s selectors need to be changed as well. Then, in a well-established scraping environment the only things that have to be changed are the selectors. In this post I will dig into CSS selectors and XPATH and share some good tips with you to write effective and fast selectors for your web scraper.

    Css selectors are widely used by frontend developers to associate css properties with their html elements. For web scrapers, we can use it to navigate in the structure of an html file. If you are a beginner scraper and you’re familiar with css then I suggest that you should use css selectors over xpath, though in some cases you have to use xpath.

    Xpath is a specification which is created to help you navigate in any XML document so you can use it while you’re parsing an html file. Almost each html parsing or web scraping related library has Xpath support. It’s a more robust and powerful way to locate elements than css selectors.

    Elements that has x class. Selects all elements that have x class

    Element is a direct or non-direct descendant of x.

    First element that is immediately preceded by x

    Element is a direct child of x.

    All elements that is preceded by x

    Element that has y attribute.

    Element’s y attribute is “z”.

    Elements that is the last child of its parent.

    Elements that have no children.

    Start searching from root node.

    Start searching from the start of the document.

    Elements that has y class.

    Selects elements that are x or y. Searching in the whole document.

    Elements that has y attribute which are z.

    Element is direct descendant of y and y is direct descendant of x.

    The Nth y element that is a child of x.

    4 Basic Tips to Write Effective Selectors Link to heading

    • Be specific if necessary and at the same time use as short selectors as you can.
    • Know the HTML structure of the website thoroughly. Take time to go over it.
    • Maintain the selectors. If the layout changed you probably need to change your code.
    • Write selectors for yourself. Try to avoid tools.

    It can take a lot of time to figure out and test your selectors especially if it is a large project. If you are not afraid of messy CSS Selectors or XPATH or simply you don’t want to waste time writing your own selectors you can use one of the amazing tools below to make your job easier. These tools will generate your desired selectors and xpath. Be aware that these tools don’t necessarily create the most readable and most efficient piece of code. Also, they sometimes generate wrong strings that doesn’t select what you need.

    Источник

    Using XPaths and CSS Selectors

    Selectors are used to locate elements on a webpage. ObservePoint uses them to find items to click on, enter text into, and to do other interactions in Journey and audit actions. The default selector is an element’s ID but alternate selectors can be used to increase the likelihood of a successful Journey when there is no ID on the target element.

    Alternate Selector Types

    The name attribute of an HTML element can be used as a selector.

    Cascading Style Sheet (CSS) selectors is a syntax used in style definitions to locate items on a web page and apply styling to them (color, font family, positioning, etc). These selectors can also be used with jQuery to locate HTML elements.

    XML Path Language (XPath) is a syntax for locating elements in structured documents such as an XML document or web page. XPath defines a kind of hierarchy of elements in the document.

    You do not need to know XPath or CSS (though it might be helpful) in order to use them in actions.

    The selectors are evaluated in an order as the Journey runs. If the ID does not resolve to a valid HTML element, the Journey will try other selector types according to the following order before failing:

    Note: Only the Chrome engine is compatible with XPath or CSS selectors in actions. If you want the CSS or XPath to be used, make sure the Chrome engine option is selected in the Journey or audit setup.

    Finding a CSS Selector or XPath

    If you do not know a CSS Selector or XPath for an element, you can find it manually from the browser’s Developer Tools. The general procedure is as follows, though there may be slight differences from browser to browser:

    1. Right click on an element
    2. Choose Inspect
    3. Locate the element in the Elements panel of the Developer Tools
    4. Right click on the element’s line
    5. Choose Copy -> Copy Selector or Copy -> Copy XPath
    6. Paste the result into the ID field of an action

    A CSS selector for the blog link’s anchor tag might look like this:
    a[href=’/blog’

    An XPath to the same blog link (above) on jpstyle.us might look like this:

    Validating CSS Selectors as Input and Click Functions for Journeys

    Testing in the Browser

    You can test your XPath or CSS selector in Chrome’s JavaScript console by wrapping it in a statement, like this:

    For example, use the following to select the Blog link at http://jpstyle.us. The red text is the selector.

    Additional Resources

    More details about XPaths and CSS selectors is beyond the scope of this document, but there are several sites on the web that teach about them or have reference materials, including these from W3Schools.com: XPath Introduction and CSS Selectors Reference.

    Thanks for the feedback There was a problem submitting your feedback. Please try again later.

    Last updated on March 6, 2023

    Источник

    Оцените статью