C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Locating Strategies- (By CSS-Tag and Attribute)In this section, you will learn how to locate a particular web element using CSS - Tag and Attribute Selector. As we know that locating a particular web element involves inspection of its HTML codes. Follow the steps given below to locate the Textbox on the sample web page.
Note: You can choose attributes such as id, class and name along with their values when you are locating through CSS - Tag and Attribute Selector.
The Java Syntax for locating a web element through CSS - Tag and Attribute Selector is written as:
driver.findElement(By.cssSelector("Tag[Attribute=value]"))
Therefore, for locating the Textbox on the sample web page we will use the input tag with id attribute:
driver.findElement(By.cssSelector("input[id=fname]"))
Similarly, for locating the Submit button on the sample web page we will use the button tag with id attribute:
driver.findElement(By.cssSelector("button[id=idOfButton]"))
We have created a sample script for you to get a better understanding of how to use CSS - Tag and Attribute Selector. We have embedded comments in each section of code which will guide you through whole automation process.
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
public class SampleThree {
public static void main(String[] args) {
// System Property for Gecko Driver
System.setProperty("webdriver.gecko.driver","D:\\GeckoDriver\\geckodriver.exe" );
// Initialize Gecko Driver using Desired Capabilities Class
DesiredCapabilities capabilities = DesiredCapabilities.firefox();
capabilities.setCapability("marionette",true);
WebDriver driver= new FirefoxDriver(capabilities);
// Launch Website
driver.navigate().to("https://www.testandquiz.com/selenium/testing.html");
// Click on the textbox and send value
driver.findElement(By.cssSelector("input[id=fname]")).sendKeys("Selenium Tutorials");
// Click on the Submit button using click() command
driver.findElement(By.cssSelector("button[id=idOfButton]")).click();
// Close the Browser
driver.close();
}
}
Next TopicLocating Strategies- By CSS
|