How to Enter Username and Password in Selenium Webdriver Java
Selenium is an
open-source
web-based automation tool that is
implemented using a web driver. We will be using geckodriver
because Selenium 3 enables
geckodriver as the default WebDriver implementation for Firefox.
Pre-requisites:
- geckodriver.exe
- maven dependency selenium
<dependency> <groupid>org.seleniumhq.selenium</groupid> <artifactid>selenium-java</artifactid> <version>4.1.1</version> </dependency>
Steps:
It's a 4 steps process:
-
Set
webdriver.gecko.driver
and its'path
as a system property. - Set the firefox diver and browse to the website link.
-
Get username and password web element;
input
usingwebdriver.findElement()
function and css selector. - Send the values as keys.
Let’s see all the above steps in the code. We will use
webelement.sendKeys(CharSequence....KeystoSend)
function to enter username and password.
import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; import java.util.List; public class EnterUsernamePassword { public static String GECKODRIVER_PATH = "F:\\WORK\\SeleniumShortTasks\\UsernamePassword\\src\\main\\resources\\geckodriver.exe"; public static void main(String[] args) { //set firefox webdriver System.setProperty("webdriver.gecko.driver", GECKODRIVER_PATH); WebDriver driver = new FirefoxDriver(); //get the firefox browser & Browse the Website , a login form String siteLink = "https://portal.alnafi.com/users/sign_in"; driver.get(siteLink); String login_user = "yourUsername"; String login_key = "yourPassword"; //Get username input-element WebElement username = driver.findElements(By.cssSelector("input.form__control")).get(0); username.sendKeys(login_user); username.submit(); //get password input-element WebElement password = driver.findElements(By.cssSelector("input.form__control")).get(1); password.sendKeys(login_key); //get sign-in button WebElement signIn = driver.findElement(By.cssSelector("input.button.button-primary.g-recaptcha")); //click signIn.click(); } }
Output:
- source code
- geckdriver.exe
Comments
Post a Comment