How to handle .jnlp download file operation in Chrome 53 from Selenium Webdriver - google-chrome

I am trying to write code in Selenium Webdrvier 3.0 + Java 1.8 + Chrome 53 for an application which needs to download and execute a .jnlp file after invoking a get(url). I am not sure whether this could be handled in Selenium webdriver or not?
As I am new to selenium any help or guidance for handling these Windows Pop will be really helpful for me.
Below is the piece of code :
if(browser.contains("CHROME") || browser.equalsIgnoreCase("chrome"))
{
ChromeOptions options = new ChromeOptions();
options.addArguments("--test-type");
options.addArguments("--disable-extensions");
capability = DesiredCapabilities.chrome();
capability.setBrowserName("chrome");
capability.setCapability(ChromeOptions.CAPABILITY, options);
}
capability.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
browserDriver = new RemoteWebDriver(new URL(nodeAddress), capability);
browserDriver.manage().timeouts().pageLoadTimeout(1000, TimeUnit.SECONDS);
browserDriver.manage().timeouts().implicitlyWait(90, TimeUnit.SECONDS);
browserDriver.manage().window().maximize();
browserDriver.get(applicationUrl);
logger.info("WebDriver successfully defined with Session ID:" + browserDriver.getSessionId() + ", Page Title:" + browserDriver.getTitle() + " and URL: " + browserDriver.getCurrentUrl());
Image attached : http://i.stack.imgur.com/esfpk.jpg

The button you are trying to click is part of Chrome's UI and not part of the webpage so Selenium cannot interact with it. From the googling I've done, this is apparently an issue that people have reported as a bug and there is no consistent workaround.

I've found a workaround via Selenium + Python (but similar thing should be feasible in Java too). In Python I just click programmatically on the notification in Chrome UI to allow downloading and installation of the jnlp file (with help of win32api and win32con - I needed it for Win only). See details here
Webscraping is now much easier for me :)

Related

selenium-chromedriver: Is it possible to access everything in the browser Inspector-Network page?

In Chrome, in F12-Network there are lots of network requests, for example for stackoverflow homepage there are:
- stackoverflow.com
- jquery.min.js
- stub.en.js?v=xxxxxxxxx
- stacks.css?v=xxxxxxxxx
- ...
Is it possible to get these requests?
It's not clear from question, but I guess you were to access all these requests via Selenium API. Yes, it became possible with Selenium 4.
Sample below shows catching requests on the google page
ChromeDriver driver = new ChromeDriver(); // driver should be of type ChromeDriver
DevTools chromeDevTools = driver.getDevTools();
chromeDevTools.createSession();
chromeDevTools.send(Network.enable(Optional.empty(), Optional.empty(), Optional.empty()));
chromeDevTools.addListener(Network.requestWillBeSent(),
req -> {
System.out.println(String.format("Sent %s request to %s",
req.getRequest().getMethod(),
req.getRequest().getUrl()
));
});
driver.get("https://www.google.com");
chromeDevTools.send(Network.disable());
driver.close();

Selenium Java ChromeDriver - How to disable attached sites

When loading a web page, it sometimes keep hanging on loading sites like "google analytics", "gstatic.com", etc.
It sometimes hangs forever.
Is there a way to disable this behavior?
Working with Selenium 3.4.0 along with the latest chromedriver 2.29 & latest Google Chrome 58.0 to restrict the loading of the sites you can take help of pageLoadStrategy through DesiredCapabilities Class as follows:
System.setProperty("webdriver.chrome.driver", "C:\\Utility\\BrowserDrivers\\chromedriver.exe");
ChromeOptions options = new ChromeOptions();
options.addArguments("start-maximized");
options.addArguments("disable-infobars");
DesiredCapabilities c1 = DesiredCapabilities.chrome();
c1.setCapability(ChromeOptions.CAPABILITY, options);
c1.setCapability("pageLoadStrategy", "none");
WebDriver driver1 = new ChromeDriver(c1);
Navigation navigate = driver1.navigate();
navigate.to("https://gmail.com");
Disclaimer:
Using this capability you cannot be sure if the HTML DOM have completely loaded or not for you to continue working with the WebElements present on that Webpage.
Let me know if this Answers your Question.

Getting chrome.exe popup opened while executing selenium scripts

I'm getting a popup opened from location C:\Program Files\Google\Chrome\application\chrome.exe while executing selenium webdriver scripts in chrome browser.
This one is throwing the error as session timed out.
Note: The same codebase is working fine in other machine.
Can you please help me out to get this sorted.
The code I am using is as below:-
var arr = new string[7] {
"--start-maximized", "--ignore-certificate-errors", "--disable-popup-blocking", "--disable-default-apps", "--auto-launch-at-startup", "--always-authorize-plugins", "--user-agent= " + FrameGlobals.userAgentValue
};
chromeCapabilities.AddArguments(arr);
WebDriverObj = new ChromeDriver(chromeCapabilities);
This is how i'm initiating the chrome browser. not mentioning any version inside codebase.
enter image description here
Thanks in advance.
Hema
You can add all your argument one by one and then pass it to the Chromedriver as below:-
WebDriver driver=null;
System.setProperty("webdriver.chrome.driver","./src//lib//chromedriver");
DesiredCapabilities capabilities = DesiredCapabilities.chrome();
ChromeOptions options = new ChromeOptions();
options.addArguments("test-type");
options.addArgument("--start-maximized");
options.addArguments("--disable-web-security");
options.addArguments("--allow-running-insecure-content");
capabilities.setCapability("chrome.binary","./src//lib//chromedriver");
capabilities.setCapability(ChromeOptions.CAPABILITY, options);
driver = new ChromeDriver(capabilities);
driver.get("https://www.google.com/");
Replace your argument with above-mentioned arguments
Hope it will help you :)

play DRM content in chrome driver

I'm writing some selenium tests for a HTML5 player playing DRM content, the player works fine in Chrome when I test it manually, but nothing is loaded or played in the latest chrome driver if I run my test cases.
Is it because of the drm content isn't authorized to play in chrome driver or something else?
I have no issues running tests for other functions written in selenium.
Any ideas?
Chromedriver launches Chrome with --disable-component-update switch by default, which disables the NaCl (Native Client) support, which is in turn required to load DRM modules (e.g. Widevine Modular DRM).
To get around this, you need to tell the driver not to launch Chrome with this switch, by building the driver with excludeSwitches option, specifying disable-component-update parameter. For example (JS):
var webdriver = require('selenium-webdriver');
var chrome = require("selenium-webdriver/chrome");
var capabilities = new webdriver.Capabilities.chrome();
var chromeOptions = {
'args': ['--user-data-dir=C:/ChromeProfile'], // start with pre-configured Chrome profile
'excludeSwitches': ['disable-component-update'] // stop breaking Native Client support
};
capabilities.set('chromeOptions', chromeOptions);
var driver = new webdriver.Builder().
withCapabilities(capabilities).
build();
driver.get('http://...');
Or using Python bindings:
from selenium import webdriver
def buildDriver():
options = webdriver.ChromeOptions()
options.add_experimental_option('excludeSwitches', ['disable-component-update'])
options.add_argument('--user-data-dir=C:/Temp/ChromeProfile')
return webdriver.Chrome(chrome_options=options)
Hope that helps..
-- ab1
Issue 886: Enabled PNaCl Components in ChromeDriver - Enhancement
If you cannot get #Chainik's answer to work, try this out. It worked for me.
As per https://bugs.chromium.org/p/chromedriver/issues/detail?id=1140 you can work around this issue by doing a few things.
manually start chrome from terminal/command prompt with these command line arguments --
google-chrome --user-data-dir=/path/to/any/custom/directory/home/user/Desktop/Chromedir --profile-directory="Profile 1" --remote-debugging-port=7878
make sure "Profile 1" is already existing in the same --user-data-dir (make usre Profile 1 has necessary chrome://components/ to run Netflix when launched manually)
you can use any free port in place of 7878
verify that http://localhost:7878 is running and returns value.
now connect to the remote-debugging-port=7878 via chromedriver with code below
Verify chrome://components/
I put mine into a .bat file, but you could do the same for a bash script or whatever:
C:/Program Files (x86)/Google/Chrome/Application/chrome.exe --user-data=c:/temp/chromeprofile --profile-directory="Profile 1" --remote-debugging-port=7878
Then set the debugger address in your code to use the browser:
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
cr_options = Options()
# This line is where the "magic" happens.
cr_options.add_experimental_option('debuggerAddress','127.0.0.1:7878')
browser = webdriver.Chrome(chrome_options=cr_options)
browser.get('https://www.google.com')
browser.get('chrome://components/')
I'm post a java version of Chainik's answer as a reference for those using Java, please let me know if there's anything wrong.
ChromeOptions options = new ChromeOptions();
List<String> list = new ArrayList<String>();
list.add("disable-component-update");
options.setExperimentalOption("excludeSwitches", list);
options.addArguments("user-data-dir=/Users/myname/Library/Application Support/Google/Chrome/Default");
java.lang.System.setProperty("webdriver.chrome.driver","/usr/bin/chromedriver");
Webdriver driver = new ChromeDriver(options);
Here is an article about chromedriver capabilities and options.
This is late but might help someone else. I was able to get around this and play videos by not using a headless browser.
In Python,
options = Options()
options.headless = False
webdriver.Chrome(executable_path='path/to/chromedriver', options=options)

Accept permission request in chrome using selenium

I have a HTML/Javascript file with google's web speech api and I'm doing testing using selenium, however everytime I enter the site the browser requests permission to use my microphone and I have to click on 'ALLOW'.
How do I make selenium click on ALLOW automatically ?
Wrestled with this quite a bit myself.
The easiest way to do this is to avoid getting the permission prompt is to add --use-fake-ui-for-media-stream to your browser switches.
Here's some shamelessly modified code from #ExperimentsWithCode's answer:
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
chrome_options = Options()
chrome_options.add_argument("--use-fake-ui-for-media-stream")
driver = webdriver.Chrome(executable_path="path/to/chromedriver", chrome_options=chrome_options)
#ExperimentsWithCode
Thank you for your answer again, I have spent almost the whole day today trying to figure out how to do this and I've also tried your suggestion where you add that flag --disable-user-media-security to chrome, unfortunately it didn't work for me.
However I thought of a really simple solution:
To automatically click on Allow all I have to do is press TAB key three times and then press enter. And so I have written the program to do that automatically and it WORKS !!!
The first TAB pressed when my html page opens directs me to my input box, the second to the address bar and the third on the ALLOW button, then the Enter button is pressed.
The python program uses selenium as well as PyWin32 bindings.
Thank you for taking your time and trying to help me it is much appreciated.
So I just ran into another question asking about disabling a different prompt box. It seems there may be a way for you to accomplish your goal.
This page lists options for starting chrome. One of the options is
--disable-user-media-security
"Disables some security measures when accessing user media devices like webcams and microphones, especially on non-HTTPS pages"
So maybe this will work for you:
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
chrome_options = Options()
chrome_options.add_argument("--disable-user-media-security=true")
driver = webdriver.Chrome(executable_path="path/to/chromedriver", chrome_options=chrome_options)
Beware of Mohana Latha's answer for JAVA!
The code is only pressing the buttons and NEVER releasing them. This will bring bunch of issues later on.
Use this instead:
// opening new window
Robot robot;
try {
robot = new Robot();
robot.keyPress(KeyEvent.VK_CONTROL);
robot.delay(100);
robot.keyPress(KeyEvent.VK_N);
robot.delay(100);
robot.keyRelease(KeyEvent.VK_N);
robot.delay(100);
robot.keyRelease(KeyEvent.VK_CONTROL);
robot.delay(100);
} catch (AWTException e) {
log.error("Failed to press buttons: " + e.getMessage());
}
Building on the answer from #Shady Programmer.
I tried to send Tab keys with selenium in order to focus on the popup, but as reported by others it didn't work in Linux. Therefore, instead of using selenium keys, I use xdotool command from python :
def send_key(winid, key):
xdotool_args = ['xdotool', 'windowactivate', '--sync', winid, 'key', key]
subprocess.check_output(xdotool_args)
which for Firefox, gives the following approximate sequence :
# Focusing on permissions popup icon
for i in range(6):
time.sleep(0.1)
send_key(win_info['winid'], 'Tab')
# Enter permissions popup
time.sleep(0.1)
send_key(win_info['winid'], 'space')
# Focus on "accept" button
for i in range(3):
time.sleep(0.1)
send_key(win_info['winid'], 'Tab')
# Press "accept"
send_key(win_info['winid'], 'a')
[Java]: Yes there is a simple technique to click on Allow button using Robot-java.awt
public void allowGEOLocationCapture(){
Robot robot = null;
try {
robot = new Robot();
robot.keyPress(KeyEvent.VK_TAB);
robot.keyPress(KeyEvent.VK_ENTER);
robot.delay(600);
} catch (AWTException e) {
getLogger().info(e);
}
}
You can allow using add_experimental_option as shown below.
from selenium.webdriver.chrome.options import Options
chrome_options = Options()
chrome_options.add_experimental_option('prefs',{'profile.default_content_setting_values.notifications':1})
driver = webdriver.Chrome(chrome_options=chrome_options)
Do it
For android chrome it really work!
adb -s emulator-5554 push <YOU_COMPUTER_PATH_FOLDER>/com.android.chrome_preferences.xml /data/data/com.android.chrome/shared_prefs/com.android.chrome_preferences.xml
File config here https://yadi.sk/d/ubAxmWsN5RQ3HA
Chrome 80 x86
or you can save the settings file after ticking the box with your hands, in adb its "pull" - command