Search code examples
javaseleniumselenium-webdriverjava.util.scanneruser-input

How automate accessing an url appending the user provided language using Selenium with Java?


I have to automate the URL with the language as parameter in the URL. I want the base URL to be same and the user entered language(text) should be appended after my base URL and the browser should redirect to that complete URL.

For eg. MY Base URL :- https://www.nokia.com

If the user enters :- en-in

I want my automation script to redirect the browser to https://www.nokia.com/en-in.


Solution

  • To open the URL with the language as parameter within the URL supplied by the user you can use Java's Scanner() and you can use the following solution:

    • Code Block:

      import java.util.Scanner;
      import org.openqa.selenium.WebDriver;
      import org.openqa.selenium.chrome.ChromeDriver;
      import org.openqa.selenium.chrome.ChromeOptions;
      
      public class userURL {
      
          public static void main(String[] args) {
      
              String baseURL = "https://www.nokia.com";
              Scanner scanner = new Scanner(System.in);
              System.out.println("Enter your language: ");
              String lang = scanner.nextLine();
              scanner.close();
              System.setProperty("webdriver.chrome.driver", "C:\\SeleniumUtilities\\BrowserDrivers\\chromedriver.exe");
              ChromeOptions options = new ChromeOptions();
              options.addArguments("start-maximized");
              options.addArguments("--disable-extensions");
              options.addArguments("disable-infobars");
              WebDriver driver = new ChromeDriver(options);
              driver.get(baseURL + "/" + lang);
              System.out.println(driver.getCurrentUrl());
          }
      }
      
    • Console Output:

      Enter your language: 
      en-in
      Starting ChromeDriver 2.46 (62ebf098771772160f391d75e589dc567915b233) on port 2306
      Only local connections are allowed.
      May 14, 2019 8:37:11 PM org.openqa.selenium.remote.ProtocolHandshake createSession
      INFO: Detected dialect: OSS
      https://www.nokia.com/en-in