Web automation testing is an essential part of modern software development and it requires precise control over the elements on a website. Selenium is a popular tool for automating web browsers and it provides multiple ways to locate elements on a web page. In this article, we will go through 5 hands-on exercises that demonstrate how to locate website elements using different methods in Selenium Java.
SOME TEST CASES OF LOCATING WEBSITE ELEMENTS
- Test case for locating an element by its ID: In this test case, the website element is located using its unique ID attribute.
- Test case for locating an element by its class name: In this test case, the website element is located using its class name attribute.
- Test case for locating an element by its tag name: In this test case, the website element is located using its HTML tag name.
- Test case for locating an element by its name attribute: In this test case, the website element is located using its name attribute.
- Test case for locating an element by its xpath: In this test case, the website element is located using its xpath, which is a syntax for locating elements in an XML document.
SAMPLE EXERCISES
- Test case for locating an element by its ID:Exercise: Find the input field with ID “username” and send the keys “Test User” to it. Answer:
python
WebElement username = driver.findElement(By.id("username"));
username.sendKeys("Test User");
2. Test case for locating an element by its class name: Exercise: Find the button with class name “submit” and click it. Answer:
java
WebElement submitBtn = driver.findElement(By.className("submit"));
submitBtn.click();
3. Test case for locating an element by its tag name:
Exercise: Find the first anchor tag on the page and retrieve its text. Answer:
java
WebElement firstLink = driver.findElement(By.tagName("a"));
String linkText = firstLink.getText();
4. Test case for locating an element by its name attribute:
Exercise: Find the radio button with name “gender” and value “male” and select it. Answer:
css
WebElement maleRadio = driver.findElement(By.xpath("//input[@name='gender'][@value='male']"));
maleRadio.click();
5. Test case for locating an element by its xpath:
Exercise: Find the element with text “Forgot Password?” using xpath and retrieve its text. Answer:
vbnet
WebElement forgotPassword = driver.findElement(By.xpath("//*[text()='Forgot Password?']"));
String text = forgotPassword.getText();
In conclusion, locating elements on a web page is a crucial step in web automation testing, and Selenium provides multiple methods to achieve this. By working through these 5 hands-on exercises, you will have a solid understanding of how to locate website elements in Selenium Java. This knowledge will be instrumental in writing robust and reliable web automation tests. Keep practicing and improving your skills, and you will soon become a master in web automation testing with Selenium.