I intend to perform some tests by using selenium with multiple web browsers. To distinguish between the different web drivers, I use the following line of code:
((RemoteWebDriver) driver).getCapabilities().getBrowserName();
This will return a String indicating the web browser that is used by the driver object. However, for my Opera WebDriver object this will give me the String 'chrome'. I have tried changing this by explicitly setting the browser name to 'opera' using DesiredCapabilities:
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setBrowserName("opera");
WebDriver driver = new OperaDriver(capabilities);
Unfortunately, this does not fix my problem. How do I effectively change the web browser name?
Your basic requirement is to identify browser initialization if I'm right, which can be done by getting user-agent from your browser using JavascriptExecutor as following:
String userAgent = (String) ((JavascriptExecutor) driver).executeScript("return navigator.userAgent;");
//following is for identifying opera browser initialization
if(userAgent.contains("OPR/"){
System.out.println("Browser currently in use is Opera");
}
Similarly you can identify other browser initilisation by referring this link
Unfortunately , you would not be able to change the BrowserName.
What instead you can try is to create function for specifically handling multiple browsers: -
package multiBrowser;
import org.testng.annotations.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.openqa.selenium.firefox.internal.ProfilesIni;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.opera.OperaDriver;
import org.testng.annotations.Parameters;
public class MultiBrowserClass {
WebDriver driver;
#Test
#Parameters("browser")
public void multiBrowsers(String browserName) throws InterruptedException{
if(browserName.equalsIgnoreCase("firefox")){
System.setProperty("webdriver.firefox.marionette","D:\\My Work\\Setup\\JAR\\geckodriver.exe");
ProfilesIni profile = new ProfilesIni();
FirefoxProfile myprofile = profile.getProfile("default");
driver = new FirefoxDriver(myprofile);
}
if(browserName.equalsIgnoreCase("chrome")){
System.setProperty("webdriver.chrome.driver", "D:\\My Work\\Setup\\JAR\\driver\\chromedriver.exe");
driver = new ChromeDriver();
}
else if(browserName.equalsIgnoreCase("IE")){
System.setProperty("webdriver.ie.driver", "D:\\My Work\\Setup\\JAR\\driver\\IEDriverServer.exe");
driver = new InternetExplorerDriver();
}
else if(browserName.equalsIgnoreCase("opera")){
System.setProperty("webdriver.opera.driver", "D:\\My Work\\Setup\\JAR\\driver\\operadriver.exe");
driver = new OperaDriver();
}
driver.manage().window().maximize();
driver.navigate().to("https://");
System.out.println(driver.getTitle());
driver.findElement(By.xpath("//div[#id='navbar-main']/ul/li[5]/a")).click();
driver.findElement(By.xpath("//div[#id='navbar-main']/ul/li[5]/ul/li/a")).click();
Thread.sleep(3000);
driver.findElement(By.name("email")).clear();
driver.findElement(By.name("email")).sendKeys("abc#mm.kk");
driver.findElement(By.name("password")).clear();
driver.findElement(By.name("password")).sendKeys("1qaz2wsx");
Thread.sleep(3000);
driver.findElement(By.xpath("//form[#id='loginform']/div[8]/button")).click();
Thread.sleep(5000);
if(driver.getPageSource().contains("Welcome abc#mm.kk")){
System.out.println("User Successfully logged in");
}else{
System.out.println("Username or password you entered is incorrect");
}
driver.quit();
}
}
=======
Related
breaking my head over the following piece of code in Java, trying to solve a recaptcha for my selenium tests at work before implementing them.
The use case I use: https://www.google.com/recaptcha/api2/demo
WebDriver driver = Selenium.getInstance();
Selenium.goToWebPage("https://www.google.com/recaptcha/api2/demo");
WebDriverWait wait = new WebDriverWait(driver, 5);
List<WebElement> allIFrames = SeleniumUtil.getWebElementNicelyByTagName(driver, wait, "iframe");
if(allIFrames == null){
return;
}
Optional<WebElement> captchaIFrame = allIFrames.stream().filter(webElement -> webElement.getAttribute("src").contains("recaptcha/api2/anchor")).findFirst();
if(!captchaIFrame.isPresent()){
return;
}
WebDriver frame = driver.switchTo().frame(captchaIFrame.get());
//System.out.println(frame.getPageSource());
WebElement recaptchaTokenElement = SeleniumUtil.getWebElementNicelyByXPath(frame, wait, "//*[#type='hidden']");
System.out.println(recaptchaTokenElement);
So with the system.outs i'm trying to find my way to the captcha token, but every time it returns a null element. What the SeleniumUtil so far does is mainly:
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(xpath)));
return driver.findElement(By.xpath(xpath));
And the same for By.CssSelector etc.
I am already in the right IFrame, because the page source is printen out correctly, but searching by #recaptcha-token (cssselector), recaptcha-token (id), //*#id="recaptcha-token" does not work.
Maybe someone can help me with this?
There is a iFrame where the driver needs to be switched to.
After few tries I've got:
standard chromedriver setup:
package selenium;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
public class WebDriverSetup {
public static String userDir = System.getProperty("user.dir");
public static String chromedriverPath = userDir + "\\resources\\chromedriver.exe";
public static WebDriver driver;
public static WebDriver startChromeDriver() {
System.setProperty("webdriver.chrome.driver", chromedriverPath);
ChromeOptions options = new ChromeOptions();
options.addArguments("--start-maximized");
driver = new ChromeDriver(options);
driver.manage().window().maximize();
return driver;
}
}
And getting the token:
package selenium;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
public class GoogleRecaptchaDemo extends WebDriverSetup {
public static void main(String[] args) {
WebDriver driver = startChromeDriver();
driver.get("https://www.google.com/recaptcha/api2/demo");
List<WebElement> frames = driver.findElements(By.tagName("iframe"));
driver.switchTo().frame(frames.get(0));
WebElement rc = driver.findElement(By.id("recaptcha-anchor-label"));
rc.click();
WebElement recaptchaToken = driver.findElement(By.id("recaptcha-token"));
String token = recaptchaToken.getAttribute("value");
System.out.println(token);
driver.quit();
}
}
My output, last line is the token:
Starting ChromeDriver 86.0.4240.22 (398b0743353ff36fb1b82468f63a3a93b4e2e89e-refs/branch-heads/4240#{#378}) on port 25872
Only local connections are allowed.
Please see https://chromedriver.chromium.org/security-considerations for suggestions on keeping ChromeDriver safe.
ChromeDriver was started successfully.
Pro 01, 2020 4:30:45 ODP. org.openqa.selenium.remote.ProtocolHandshake createSession
INFO: Detected dialect: W3C
03AGdBq24MumCzjDlQCrcb4N3BuIiHm6O7V5IKSNGP1wChYe9g1Vc1GR7_NsvKqKV1Jzb5yLUXCB-ko8satP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IaJYWHrQAz4odFQZaD-HZ4qnRZlJlnMzV31_o3_NLl-_2CGSywE8kuJf8wAIIplncfDdHSIlUn7WhrIOrSOX83NdKaQYAlTqLI9CTSTjaA3AyhG5OcF2dukVeACOItczNBSJcZeenTMCo1Es986nt770A3tQYC7S9r2ESxlYJl-eWGo8SKuM9udx7ZuO5lKgW-V-EUg1I-YFSoguRmGzUK-liu2-afTBn4X-97VXuiv-tdcKdi9Bx4DtlhqzNGvVbQmIOND
Why did this happen? Chrome opens but the URL does not open with the code.
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class Id {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "E:\\chromedriver\\chromedriver.exe"); //open browser
WebDriver driver = new ChromeDriver();
**driver.get("google.co.in"); //open URL**
driver.findElement(By.name("q")).sendKeys("Quadkast" + Keys.ENTER);
}
}
You need to give http/https protocol along with the url in the get() method
driver.get("http://www.google.com");
or
driver.get("https://google.com");
String baseUrl = "http://demo.guru99.com/test/login.html";
driver.get(baseUrl);
// Get the WebElement corresponding to the Email Address(TextField)
WebElement email = driver.findElement(By.id("email"));
// Get the WebElement corresponding to the Password Field
WebElement password = driver.findElement(By.name("passwd"));
To send the credentials within the Email address and Password field you can use the following Locator Strategies:
Code Block:
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class A_demo
{
public static void main(String[] args) throws Exception
{
System.setProperty("webdriver.chrome.driver", "C:\\Utility\\BrowserDrivers\\chromedriver.exe");
ChromeOptions options = new ChromeOptions();
options.addArguments("start-maximized");
options.setExperimentalOption("excludeSwitches", Collections.singletonList("enable-automation"));
options.setExperimentalOption("useAutomationExtension", false);
WebDriver driver = new ChromeDriver(options);
driver.get("http://demo.guru99.com/test/login.html");
new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.cssSelector("input#email"))).sendKeys("saikiran_thotakura");
driver.findElement(By.cssSelector("input#passwd")).sendKeys("saikiran_thotakura");
}
}
Browser Snapshot:
I am new to Appium and I was trying to execute a simple program which performs a click operation. But the click operation is not happening. Here is the code:
package com.android.touchactionss;
import java.net.MalformedURLException;
import java.net.URL;
import org.openqa.selenium.remote.DesiredCapabilities;
import io.appium.java_client.android.AndroidDriver;
public class Sample {
public static void main(String[] args) throws InterruptedException, MalformedURLException {
DesiredCapabilities cap = new DesiredCapabilities();
cap.setCapability("platformName", "Android");
cap.setCapability("deviceName", "xiaomi-2014818-204648717d62");
cap.setCapability("version", "5.1.1");
cap.setCapability("appActivity", "com.mediamushroom.copymydata.app.EasyMigrateActivity");
cap.setCapability("appPackage", "com.mediamushroom.copymydata");
AndroidDriver<?> driver = new AndroidDriver<>(new URL("http://127.0.0.1:4723/wd/hub"), cap);
Thread.sleep(5000);
try{
System.out.println("STARTED");
driver.findElementByAndroidUIAutomator(
"new UiSelector().resourceId(\"com.mediamushroom.copymydata:id/NextButton\")");
//driver.findElement(By.id("//*[#resource-id='com.mediamushroom.copymydata:id/NextButton']"));
System.out.println("ENDED");
}
catch(Exception exception){
exception.printStackTrace();
}
Thread.sleep(5000);
driver.quit();
}
}
No exception is thrown but the click operation didn't happen. I tried with both driver.findElement(By.id("")) and driver.findElementByAndroidUIAutomator() method. But none of them worked. I have attached the object properties screen.
Versions used: appium software version 1.6.2
appium java_client version 6.1.0
selenium 3.13
First, add the following import:
import io.appium.java_client.android.AndroidElement;
Next change your code:
AndroidDriver<?> driver = new AndroidDriver<>(new URL("http://127.0.0.1:4723/wd/hub"), cap);
to:
AndroidDriver<AndroidElement> driver = new AndroidDriver<AndroidElement>(new URL("http://127.0.0.1:4723/wd/hub"), cap);
You might need to change the URL to 0.0.0.0 but it depends on what your Appium Server settings are. They may be correct they way it is now.
Lastly, you need to use the following method to click the element:
driver.findElement(By.id("com.mediamushroom.copymydata:id/NextButton")).click();
Hi here is example in next few lines, try to use some testing framework, Junit, TestNg, I've removed main, used TestNG with this example:
Start Appium server:
Appium GUI (https://github.com/appium/appium-desktop/releases/tag/v1.6.2)
Appium via console : appium --address 127.0.0.1 --port 4723
when Appium server is up-an-running, call this code:
import io.appium.java_client.MobileElement;
import io.appium.java_client.android.AndroidDriver;
import org.openqa.selenium.By;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import java.net.MalformedURLException;
import java.net.URL;
public class TestAppium {
AndroidDriver<MobileElement> driver;
#BeforeTest
public void setup() {
DesiredCapabilities cap = new DesiredCapabilities();
cap.setCapability("platformName", "Android");
cap.setCapability("deviceName", "emulator-5554"); //used emulator, but should be set devices guid in Your case "xiaomi-2014818-204648717d62"
cap.setCapability("version", "5.1.1");
cap.setCapability("appActivity", "com com.mediamushroom.copymydata.app.EasyMigrateActivity");
cap.setCapability("appPackage", "com.mediamushroom.copymydata");
try {
driver = new AndroidDriver<>(new URL("http://127.0.0.1:4723/wd/hub"), cap);
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
#Test
public void testAppiumSimulator() {
MobileElement element = driver.findElement(By.id("NextButton"));
element.click();
// do some Assertion
Assert.assertTrue(//some condition//);
}
#AfterTest
public void tearDown() {
driver.quit();
}
}
And this is an simple Appium test...
Hope this helps,
I am new to WebDriver, i am facing an issue on browser window switching.
I googled for my query resolution and the answer i found best is still not working for me.
Here is my code :
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.annotations.BeforeSuite;
public class FrameWorkBase {
public static WebDriver driver;
public static WebDriverWait wait;
public static String firstWindow,secondWindow;
#BeforeSuite
public void startDriver() throws Exception{
driver= new FirefoxDriver(); // this firefox window is to open survey
driver.manage().window().maximize();
wait=new WebDriverWait(driver, 40);
driver.get("http://www.cricinfo.com");
firstWindow=driver.getWindowHandle();
driver=new FirefoxDriver();
driver.manage().window().maximize();
driver.get("https://translate.google.co.in/");
secondWindow=driver.getWindowHandle();
System.out.println("First window handle :" + firstWindow);
System.out.println("\n Second window handle :" + secondWindow);
driver.switchTo().window(firstWindow);
System.out.println("hello");
}
}
I am getting an error on execution as Unable to find window 'xyz' where 'xyz' is the name of first window.
Even i am printing the window name and it is displaying the same window for which it is displaying error.
Please suggest me what i am doing wrong here.
Thanks
This is happening because you have reinitialized the driver instance.
driver=new FirefoxDriver();
driver.manage().window().maximize();
driver.get("https://translate.google.co.in/");
This line has reinitialised your driver instance so what ever u try to do you won't find the window handle. If you are trying to work on both websites simultaneously, try to create another object of driver like WebDriver driver2 = new FirefoxDriver();
#Vivek has aptly answered your question. But, if you still want to open a link in a new window, you can try the below code for that:
Actions act = new Actions();
WebElement link = driver.findElement(By.xpath("//xpath of the link"));
//Opening the link in new window (works in FF and Chrome)
act.contextClick(link).sendKeys(Keys.ARROW_DOWN).sendKeys(Keys.ARROW_DOWN).sendKeys(Keys.ENTER).build().perform();
And you can switch in between them accordingly, with the use of handles. Furthermore, this link will help you handle two windows simultaneously.