Selenium CssSelector : Part III [ hash(#) notation ]


In Selenium WebDriver, the hash (#) notation is used in CSS selectors to identify an HTML element by its unique ID.

Syntax:

driver.findElement(By.cssSelector("tag#idValue"))
  • tag: Represents the HTML tag of the element.
  • #: Denotes the hash notation to target an element by its ID.
  • idValue: The specific ID value of the element you want to target.

For example consider the following code snippet.

<input id="wpName2" name="wpName" size="20" class="loginText mw-userlogin-username cdx-text-input__input" placeholder="Enter your username" tabindex="1" required="" autocomplete="username">

I have copied this from the following link- https://en.wikipedia.org/w/index.php?title=Special:CreateAccount&returnto=Form

driver.navigate().to("https://en.wikipedia.org/w/index.php?title=Special:CreateAccount&returnto=Form");

driver.findElement(By.cssSelector("input#wpName2")).sendKeys("Abcd");
  • driver.navigate().to("https://en.wikipedia.org/w/index.php?title=Special:CreateAccount&returnto=Form"): Directs the browser to the Wikipedia account creation page.
  • driver.findElement(By.cssSelector("input#wpName2")): Finds the username input field using a CSS selector with hash notation.
    • input#wpName2 specifies an <input> element with the ID wpName2.
  • .sendKeys("Abcd"): Inputs the text “Abcd” into the located username input field.