JMeter Java web driver sampler - java

I have the following Java code for a selenium web driver in JMeter:
package com.jmeter.test.scripts;
import java.io.File;
import org.testng.annotations.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.OutputType;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.TakesScreenshot;
#Test
public class SnapScreenshot
{
String fileName = UUID.randomUUID.toString();
public static void main(String[] args)
{
System.setProperty("webdriver.chrome.driver", "C:\\Apache\\apache-jmeter-5.5\\Drivers\\Chrome\\109\\chromedriver.exe");
System.setProperty("webdriver.chrome.logfile", "C:\\Temp\\driverlog.log");
System.setProperty("webdriver.chrome.verboseLogging", "true");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.manage().timeouts().pageLoadTimeout(40, TimeUnit.SECONDS);
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.get("https://www.google.com/");
Thread.sleep(5000);
File srcFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
File destFile = new File("C:\\temp\\screenshots\\" + fileName + ".png");
try
{
FileUtils.copyFile(srcFile, destFile);
}
catch (Exception ex)
{
ex.printStackTrace();
}
finally
{
driver.quit();
}
}
}
It doesn't appear to be executing:
The logfile is not created
Any System.out.println() statements I add are not executed
I'm also getting this error message: ERROR c.g.j.p.w.s.WebDriverSampler: unknown protocol: data
Not sure what I'm doing wrong. I do have the Chrome web driver configured via "jp#gc - Chrome Driver Config" but this doesn't seem to matter much.

If you're using the WebDriver Sampler you need to amend your code accordingly:
In the Chrome Driver Config specify the path to your chromedriver executable
Remove ChromeDriver instance initialization and use WDS.browser wherever you need to manipulate the browser
Switch to "groovy" language

Related

org.openqa.selenium.NoSuchElementException: Unable to locate element error

I have written the following code in JAVA using Selenium web driver using both Internet Explorer and Firefox. Everytime I am getting the same error. Tried using both "id" and "xpath" method, but still it is failing. Tried adding some delay also, still does not work.
My JAVA code for Firefox:
package ieconnector;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.Capabilities;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.remote.RemoteWebDriver;
public class FireFoxConnector {
public static void main(String[] args) {
try{
GetBrowserProperty gbp = new GetBrowserProperty();
System.setProperty("webdriver.ie.driver",gbp.getIeConnection());
System.setProperty("webdriver.gecko.driver","D:\\softwares\\Selenium\\geckodriver-v0.21.0-win64\\geckodriver.exe");
WebDriver wb = new FirefoxDriver();
Capabilities caps = ((RemoteWebDriver) wb).getCapabilities();
System.out.println("Caps is "+caps);
wb.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
//wb.navigate().to("https://somewebsite.com:22222/SSO/ui/SSOLogin.jsp");
wb.get("https://somewebsite.com:22222/SSO/ui/SSOLogin.jsp");
wb.manage().deleteAllCookies();
wb.manage().window().maximize();
//wb.findElement(By.id("usertxt")).sendKeys(("user").toUpperCase());
//wb.findElement(By.className("passtxt")).sendKeys("password");
//WebDriverWait wait = new WebDriverWait(wb,10);
//WebElement element = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("usertxt")));
wb.manage().timeouts().pageLoadTimeout(10, TimeUnit.SECONDS);
//wb.findElement(By.id("usertxt")).sendKeys("USER");
wb.findElement(By.xpath("//*[#id='usertxt']")).sendKeys("USER");
System.out.println("Testing is successful");
} catch (Exception e) {
e.printStackTrace();
}
}
}
And the following is a screenshot of the HTML code in my developer tool in IE/Firefox.
As per the HTML you have shared to locate the User ID field you can use the following solution:
cssSelector:
wb.findElement(By.cssSelector("input.txtbox#usertxt")).sendKeys("USER");
xpath:
wb.findElement(By.xpath("//input[#class='txtbox' and #id='usertxt']")).sendKeys("USER");

Unable to perform simple click operation using appium code on Android app

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,

Selenium WebDriver throwing TimoutException while invoking getScreenshotAs()

This is my code.
public static void test1() throws IOException {
System.setProperty("webdriver.chrome.driver", "data/chromedriver.exe");
drive = new ChromeDriver();
drive.manage().timeouts().pageLoadTimeout(30, TimeUnit.SECONDS);
try {
drive.get("http://youtube.com");
}catch(TimeoutException e) {
printSS();
}
}
public static void printSS() throws IOException{
String path = "logs/ss/";
File scrFile = ((TakesScreenshot)drive).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(scrFile, new File(path + "asdasdas" + ".jpg"));
}
All time when driver.get() throw TimeoutException I want to take a screenshot at browser.
But when throw TimeoutException, getScreenshotAs() from printSS() don't take screenshot because throw another TimeoutException.
Why getScreenshotAs() throw TimeoutException and how to take screenshot at browser
P.S.: Increase pageLoadTimeout time is not the answer I want.
While working with Selenium 3.x, ChromeDriver 2.36 and Chrome 65.x you need to mention the relative path of the location (with respect of your project) where you intend to store the screenshot.
I took you code and did a few minor modification as follows :
Declared driver as WebDriver instance as static and added #Test annotation.
Reduced pageLoadTimeout to 2 seconds to purposefully raise the TimeoutException.
Changed the location of String path to a sub-directory wthin the project scope as follows :
String path = "./ScreenShots/";
Added a log as :
System.out.println("Screenshot Taken");
Here is the code block :
package captureScreenShot;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.TimeoutException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.Test;
public class q49319748_captureScreenshot
{
public static WebDriver drive;
#Test
public static void test1() throws IOException {
System.setProperty("webdriver.chrome.driver", "C:\\Utility\\BrowserDrivers\\chromedriver.exe");
drive = new ChromeDriver();
drive.manage().timeouts().pageLoadTimeout(2, TimeUnit.SECONDS);
try {
drive.get("http://youtube.com");
}catch(TimeoutException e) {
printSS();
}
}
public static void printSS() throws IOException{
String path = "./ScreenShots/";
File scrFile = ((TakesScreenshot)drive).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(scrFile, new File(path + "asdasdas" + ".jpg"));
System.out.println("Screenshot Taken");
}
}
Console Output :
[TestNG] Running:
C:\Users\username\AppData\Local\Temp\testng-eclipse--153679036\testng-customsuite.xml
Starting ChromeDriver 2.36.540470 (e522d04694c7ebea4ba8821272dbef4f9b818c91) on port 42798
Only local connections are allowed.
Mar 16, 2018 5:37:59 PM org.openqa.selenium.remote.ProtocolHandshake createSession
INFO: Detected dialect: OSS
Screenshot Taken
PASSED: test1
Screenshot :
Reference
You can find a detailed discussion in How to take screenshot with Selenium WebDriver
The problem is that while Selenium waits for the page to complete loading it cannot take any other command. This is why it throws TimeoutException also from the exception handler when you try take the screenshot.
The only option I see is to take the screenshot not through Selenium, but using other means that take a screenshot of the entire desktop. I've written such a thing in C#, but I'm pretty sure you can either find a way to do it in Java too.

How to effectively change the browser name of the WebDriver object?

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();
}
}
=======

Unable to start Internet Explorer or Chrome in Selenium Webdriver (JAVA)

I am trying to start up an IE instance using Webdriver. I can't figure out why I'm receiving these errors, my code appears to be identical to every example I can find on the web.
I'm using Java and testng.
Here is the code:
import java.io.File;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.WebDriver;
public class Tests {
File file = new File("C:\\selenium\\IEDriverServer.exe");
System.setProperty("webdriver.ie.driver", file.getAbsolutePath() );
WebDriver driver = new InternetExplorerDriver();
}
The following errors are displaying, all of these errors are on the "System.setProperty" line.
Multiple markers at this line
- Syntax error on token ""webdriver.ie.driver"", invalid
FormalParameterList
- Syntax error on token(s), misplaced construct(s)
- Syntax error on tokens, FormalParameter expected instead
Please note that I have the exact same problem if I try to use Chrome with this code:
File file = new File("C:/selenium/chromedriver.exe");
System.setProperty("webdriver.chrome.driver", file.getAbsolutePath());
WebDriver driver = new ChromeDriver();
You are running your code from inside class instead of running it from inside method. Covert it to something like
import java.io.File;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.WebDriver;
public class Tests {
public static void main(String[] args) { // <-- you need a method!
File file = new File("C:\\selenium\\IEDriverServer.exe");
System.setProperty("webdriver.ie.driver", file.getAbsolutePath() );
WebDriver driver = new InternetExplorerDriver();
}
}
try this :
I'm using "mvn test" to lunch the test process so the path of the IE driver may be changed
File file = new File("classes/tools/IEDriverServer.exe");
Use IE driver with Capabilities
DesiredCapabilities caps = DesiredCapabilities.internetExplorer();
System.setProperty("webdriver.ie.driver", file.getAbsolutePath());
caps.setCapability("ignoreZoomSetting", true);
caps.setCapability("nativeEvents", false);
WebDriver driver = new InternetExplorerDriver(caps);
It may help you :)
Actually, on the updated eclipse version, you might have to use #suppressWarnings
package Login;
import java.io.File;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.WebDriver;
public class Login {
public static void main(String[] args) {
File file = new File("C:\\Users\\IEDRiverServer.exe");
System.setProperty("webdriver.ie.driver", file.getAbsolutePath() );
#SuppressWarnings("unused")
WebDriver driver = new InternetExplorerDriver();
}
}
Simple example:
public class IE {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
System.setProperty("webdriver.ie.driver", "D:\\Sathish\\soft\\SELENIUM\\LatestDownloads\\selenium\\IEDriverServer.exe");
WebDriver driver = new InternetExplorerDriver();
driver.get("www.google.com");
driver.findElement(By.id("gbqfq")).sendKeys("abc");
driver.close();
}
}
Do the below process.
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
if (browserName.equalsIgnoreCase("InternetExplorer")) {
DesiredCapabilities caps = DesiredCapabilities.internetExplorer();
System.setProperty("webdriver.ie.driver", "drivers/IEDriverServer.exe");
caps.setCapability( InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS,
true);
caps.setCapability("nativeEvents", false);
browser = new InternetExplorerDriver(caps);
Then after, In IE, from the Tools menu (or the gear icon in the toolbar in later versions), select "Internet options." Go to the Security tab. At the bottom of the dialog for each zone, you should see a check box labeled "Enable Protected Mode." Set the value of the check box to the same value,
either checked or unchecked, for each zone.
I have applied the same thing at my end, it works fine.

Categories

Resources