selenium-webdriver

Where to find docs to css selector selenium?


Given:

I can find the docs for selenium and know basic constructions. https://www.selenium.dev/documentation/webdriver/elements/locators

Expected:

I want to find the CSS selector and XPath languages for deep. In particular, I want to how to find parent of given element.

Thank you, hope foe the answers


Solution

  • The docs

    The full CSS selector spec is here. A good reference can be found in the Selectors Overview.

    The XPath 1.0 spec is here. NOTE: XPath has newer specs but the version that is supported by Selenium is 1.0.

    Some good XPath documentation can be found on MDN and a good comparison of CSS selectors and XPath is here.

    Examples

    NOTE: Depending on what you mean by, "find parent of given element", CSS selectors cannot do that... only XPath. CSS selectors can only look down the DOM where XPath can look up or down.

    A couple simple XPath examples...

    Given a simple HTML table,

    <!DOCTYPE html>
    <html>
    <body>
    
    <table>
        <tr>
            <td>
                <input id="one">
            </td>
        <tr>
    </table>
    
    </body>
    </html>
    

    Find the TD that contains the INPUT with an id of "one".

    1. Using an XPath locator, the below finds the INPUT and returns the parent.

      //td[.//input[@id='one']]
      
    2. Using python code,

      e = driver.find_element(By.ID, "one")
      parent = e.find_element(By.XPATH, "..") # finds the parent element of 'e'
      print(parent.get_attribute("outerHTML"))
      

      this prints the TD tag and it's contents.