Chrome extension is not loaded by Selenium in Java - selenium-webdriver

I want to load a chrome extension named scrapbook using Java. I searched a lot and tried different proposed methods to do so. However, none of those are working. Even it does not load the window maximized, let alone loading the extension. Here is the code:
package automationFramework;
import java.io.File;
import com.google.common.base.Function;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeDriverService;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.remote.DesiredCapabilities;
public class FirstTestCase {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "F:\\SOFTWARE\\CHROME EXTENSIONS\\chromedriver_228.exe");
String pathToExtension = "C:\\Users\\user1\\AppData\\Local\\Google\Chrome\\User Data\\Profile 1\\oegnpmiddfljlloiklpkeelagaeejfai\\0.26.3_0\\";
ChromeOptions options = new ChromeOptions();
options.addArguments("-load-extension=" + pathToExtension);
options.addArguments("-open-maximized");
WebDriver driver = new ChromeDriver(options);
driver.get("https://www.google.com");
}
}

I had the same issue, then I used the .crx file to add it on launch. I'm using python, but in Java it would be the same by using:
options.add_extension("idmgcext.crx");
the .crx file is in the same folder as the script or provide full path if in another folder you can get chrome extension for .crx file.

Related

mobile devices requests emulation using JSR223 in JMeter - No such property: driver for class

Scenario:
open main page and click on "Accept All Cookies" (JSR223 Sampler1 in Once Only controller);
open pages from the set of parametrized urls (JSR223 Sampler2 in another controller).
JSR223 Sampler1 code for main page:
import org.apache.jmeter.samplers.SampleResult; import
org.openqa.selenium.chrome.ChromeOptions; import
org.openqa.selenium.chrome.ChromeDriver; import
org.openqa.selenium.WebDriver; import org.openqa.selenium.By; import
org.openqa.selenium.WebElement; import
org.openqa.selenium.support.ui.ExpectedConditions; import
org.openqa.selenium.support.ui.WebDriverWait; import
java.util.concurrent.TimeUnit;
System.setProperty("webdriver.chrome.driver",
"vars.get("webdriver_path")");
Map<String, Object> mobileEmulation = new HashMap<>();
mobileEmulation.put("userAgent", "vars.get("userAgent")");
Map<String, Object> chromeOptions = new HashMap<>();
chromeOptions.put("mobileEmulation", mobileEmulation); ChromeOptions
options = new ChromeOptions();
options.setExperimentalOption("mobileEmulation", mobileEmulation);
ChromeDriver driver = new ChromeDriver(options);
driver.get("https://vars.get("main_page")"); WebDriverWait wait = new
WebDriverWait(driver, 20);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("xpath")));
driver.findElement(By.xpath("xpath")).click();
log.info(driver.getTitle());
JSR223 Sampler2 code for any page from the set of urls:
driver.get("https://${url}");
Error message:
Response message:javax.script.ScriptException: groovy.lang.MissingPropertyException: No such property: driver for class
Problem:
If I just copy all code from JSR223 Sampler1 to JSR223 Sampler2 and change destination url, urls are opening, but in unproper way - launching each time new browser instance, and I can't have realistic response time (for driver.get("url") only), because result provides time of Sampler work, which includes driver initialization, new browser instance start and it takes several seconds...
Could you please propose any ideas, how is possible to resolve this problem? To get all requests in 1 browser instance and to have realistic response time for all requests in JSR223 Sampler2 for browser.get("url") only?
Will appreciate for any help.
In the first JSR223 Sampler you need to store your driver instance into JMeter Variables like:
vars.putObject("driver", driver)
it should be the last line of your script
In the second JSR223 Sampler you need to get the driver instance from JMeter Variables like:
driver = vars.getObject("driver")
it should be the first line of your script
vars is the shorthand for JMeterVariables class instance, see the JavaDoc for all available functions and Top 8 JMeter Java Classes You Should Be Using with Groovy article for more information on JMeter API shorthands available for JSR223 Test Elements
P.S. the same approach with vars you should follow when executing driver.get() function like:
driver.get("https://" + vars.get("url"))

JSR233 sampler with Java to work with Selenium Webdriver (javax.script.ScriptException: In file: inline evaluation)

Trying to run Selenium Webdriver script in Jmeter using JSR233 sampler. The script works fine in Eclipse IDE, however in Jmeter facing below error.
ERROR o.a.j.p.j.s.JSR223Sampler: Problem in JSR223 script JSR223 Sampler,
message: javax.script.ScriptException: In file: inline evaluation of:
``import java.util.HashMap; import org.openqa.selenium.WebDriver; import
org.openq . . . '' Encountered "," at line 28, column 25.
in inline evaluation of: ``import java.util.HashMap; import
org.openqa.selenium.WebDriver; import org.openq . . . '' at line number 28
javax.script.ScriptException: In file: inline evaluation of: ``import
java.util.HashMap; import org.openqa.selenium.WebDriver; import org.openq .
. . '' Encountered "," at line 28, column 25.
in inline evaluation of: ``import java.util.HashMap; import
org.openqa.selenium.WebDriver; import org.openq . . . '' at line number 28
at bsh.engine.BshScriptEngine.evalSource(BshScriptEngine.java:82) ~[bsh-
2.0b6.jar:2.0b6 2016-02-05 05:16:19]
at bsh.engine.BshScriptEngine.eval(BshScriptEngine.java:46) ~[bsh-
2.0b6.jar:2.0b6 2016-02-05 05:16:19]
at javax.script.AbstractScriptEngine.eval(Unknown Source) ~[?:1.8.0_181]
Below is the script trying to execute:
import java.util.HashMap;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.By;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.openqa.selenium;
System.setProperty("webdriver.chrome.driver", "D:\\chromedriver.exe");
String downloadFilepath = "D:/MyDeskDownload";
HashMap<String, Object> chromePrefs = new HashMap<String, Object>();
// chromePrefs.put("profile.default_content_settings.popups", 0);
// chromePrefs.put("download.default_directory", downloadFilepath);
// chromePrefs.put("safebrowsing.enabled", "true");
ChromeOptions options1 = new ChromeOptions();
options1.setExperimentalOption("prefs", chromePrefs);
DesiredCapabilities cap = DesiredCapabilities.chrome();
cap.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
cap.setCapability(ChromeOptions.CAPABILITY, options1);
WebDriver driver = new ChromeDriver(cap);
driver.setJavaScriptEnabled(true);
driver.get("http://google.com/");
I have gone through below references to get above script:
Running Selenium scripts with JMeter
How to use WDS variable in BSF or JSR233 (JMeter)
We could achieve launching a browser and performing actions with Selenium Webdriver config sampler with JavaScript however since we are unable to set capabilities with WDS, we are trying to achieve the same in JSR233.
From stacktrace it looks you are using JSR223 with Beanshell or Java (which will be beanshell).
Since it's Beanshell, it doesn't understands generics (diamond operator) so this line:
HashMap<String, Object> chromePrefs = new HashMap<String, Object>();
So you need to just switch the language to Groovy to fix the problem:
Beanshell doesn't support the diamond operator to if you really want to continue wiht Beanshell - change this line:
HashMap<String, Object> chromePrefs = new HashMap<String, Object>();
to this one
HashMap chromePrefs = new HashMap();
Be aware that starting from JMeter version 3.1 it's recommended to use JSR223 Test Elements and Groovy language for scripting, the reasons are in:
Groovy supports all the modern Java language features
Groovy provides a lot of enhancements over standard Java SDK
Groovy provides much better performance than Beanshell
So consider migrating to Groovy, my expectation is that no changes will be required (you might need rewriting lambdas into closures if any, however the overhead will be minimal)

FAILED: invokeApp org.openqa.selenium.SessionNotCreatedException: A new session could not be created

import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.testng.annotations.Test;
import io.appium.java_client.android.AndroidDriver;
public class Demo {
AndroidDriver driver =null;
DesiredCapabilities capabilities;
File app = new File("/data/app/com.philips.sleepmapper.root-1/base.apk");
#Test
public void invokeApp() throws MalformedURLException
{
capabilities = new DesiredCapabilities();
capabilities.setCapability("automationName", "Appium");
capabilities.setCapability("paltformName", "Android");
capabilities.setCapability("platformVersion", "6.0.1");
capabilities.setCapability("deviceNmae", "Galaxy S6");
capabilities.setCapability("app", app.getAbsolutePath());
capabilities.setCapability("appPackage","com.philips.sleepmapper.root");
capabilities.setCapability("appactivity","com.philips.sleepmapper.activity.SplashScreenActivity");
driver = new AndroidDriver(new URL("http://127.0.0.1:4723/wd/hub"), capabilities);
}
}
When executing this code i am getting the following error:
FAILED: invokeApp org.openqa.selenium.SessionNotCreatedException: A
new session could not be created. (Original error: Bad app:
C:\data\app\com.philips.sleepmapper.root-1\base.apk. App paths need to
be absolute, or relative to the appium server.
The path to your application APK is set incorrectly. I need to know your file structure to give the exact answer, but this is what I think is wrong.
Most likely you are trying to provide the application at C:\path\to\my\project\data\app\com.philips.sleepmapper.root-1\base.apk
If you run Appium in C:\path\to\my\project and you try to pass the relative path to the APK, you are missing the dot in the Appium test code. Change the path in the code to
File app = new File("./data/app/com.philips.sleepmapper.root-1/base.apk");
To make it work from any folder (absolute path) change the code to
File app = new File("C:\path\to\my\project\data\app\com.philips.sleepmapper.root-1\base.apk");
Remember to replace path\to\my\project with the real path you are using.

Sikuli integration with Selenium Webdriver info

I have added all the required jars in the build path, but I get this error when the execution reaches Sikuli APIs
[error] ResourceLoaderBasic: checkLibsDir: libs dir is not on system path: C:\Users\general\Desktop\Sikuli\libs
[action] ResourceLoaderBasic: checkLibsDir: Please wait! Trying to add it to user's path
[info] runcmd: reg QUERY HKCU
[info] runcmd: reg QUERY HKEY_CURRENT_USER\Environment /v PATH
[error] ResourceLoaderBasic: checkLibsDir: Logout and Login again! (Since libs folder is in user's path, but not activated)
[error] Terminating SikuliX after a fatal error!
Sorry, but it makes no sense to continue!
If you do not have any idea about the error cause or solution, run again
with a Debug level of 3. You might paste the output to the Q&A board.
Here is my code
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.sikuli.script.App;
import org.sikuli.script.FindFailed;
import org.sikuli.script.Pattern;
import org.sikuli.script.Screen;
public class Sikuli_test3 {
#Test
public void functionName() throws FindFailed {
// Create a new instance of the Firefox driver
WebDriver driver = new FirefoxDriver();
// And now use this to visit Google
driver.get("http://www.google.co.in");
//WebElement element = driver.findElement( By.id("gbqfq"));
//element.sendKeys("Hello");
//element.click();
//Create and initialize an instance of Screen object
Screen screen = new Screen();
//Add image path
Pattern image = new Pattern("C:\\sikuli_images\\iam_feeling_lucky.png");
//Wait 10ms for image
screen.wait(image, 10);
//Click on the image
screen.click(image);
}
}
See if User defined environment variables %SIKULI_HOME% is present in your system and is added to the PATH environment variable. If present, restart your system. This should work.
http://doc.sikuli.org/faq/030-java-dev.html
Let me know if this helps you.

Selenium how to open a web browser to run a selenium script

I exported a script from selenium IDE 1.9.0 as Java/TestNG/RemoteControl.
I would like to run this script using TestNG within Eclipse and I want to see the script play back in Firefox browser.
I did some search online, but I could not make it work. I need some instructions and guidance on how to make the code work. Your help is greatly appreciated.
Here is my code:
import java.util.List;
import org.testng.annotations.*;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.htmlunit.HtmlUnitDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;
import static org.testng.Assert.*;
import org.testng.annotations.Test;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.AfterTest;
public class search_donor_suzy_ng //extends SeleneseTestNgHelper {
#BeforeTest
public void setUp() throws Exception {
//initizlize Firefoxbrowser:
WebDriver ffoxdriver = new FirefoxDriver();
String baseUrl = "www.google.com"; //sample URL
}
#Test
public void testSearch_donor_suzy_ng() throws Exception {
// set overall speed of the test case
selenium.setSpeed("4000");
selenium.open("/?html=openid");
selenium.click("css=input[type=\"submit\"]");
selenium.waitForPageToLoad("30000");
Thread.sleep(4000);
selenium.type("id=edit-name", "jeffshu");
selenium.type("id=edit-pass", "tEgvz9xsaNjnwe4Y");
selenium.click("id=edit-submit");
selenium.waitForPageToLoad("30000");
Thread.sleep(4000);
selenium.click("id=cmp_admin");
selenium.waitForPageToLoad("30000");
selenium.click("id=quicksearch_anchor");
selenium.click("css=img[alt=\"Member\"]");
selenium.waitForPageToLoad("30000");
selenium.type("id=search_name", "suzy");
selenium.click("css=input[type=\"image\"]");
selenium.click("link=Balagia, Suzy");
selenium.waitForPageToLoad("30000");
}
#AfterTest
public void tearDown() throws Exception {
ffoxdriver.quit();
}
}
For starters, you do need to refer to the documentation # http://docs.seleniumhq.org/docs/03_webdriver.jsp
In your code, you are intializing the driver object in your beforetest method, which you are not using. Driver is Webdriver's way of launching your browser, whereas in your testmethod you are using selenium and selenium 1 commands. As a quick step, you can replace your selenium with driver (put your declaration of driver in class scope and method scope). SeleneseTestngHelper is also selenium1.
Make sure you have the necessary webdriver jars in your project.
Certain commands in webdriver are different than selenium 1 and you might see compile erros when you do the replacement. Look at the methods available with driver. and use corresponding commands eg. Use get() of webdriver instead of open(). You can refer the javadocs for this or use your ide to get to know these.

Resources