Fitting objects in window screen using Selenium Java - java

I am trying to fit all the objects in the window (Chrome browser). Manually when I am doing it(the dimensions that I am using is 1024X786 using toggle bar, but when I am automating it using the same dimension, it's not showing the same as it was manually.
The following is the code:
driver = new ChromeDriver();
Map<String, Object> deviceMetrics = new HashMap<String, Object>();
deviceMetrics.put("width", 768);
deviceMetrics.put("height", 1024);
Map<String, Object> mobileEmulation = new HashMap<String, Object>();
mobileEmulation.put("deviceMetrics", deviceMetrics);
mobileEmulation.put("userAgent", "Mobile S");
Map<String, Object> chromeOptions = new HashMap<String, Object>();
chromeOptions.put("mobileEmulation", mobileEmulation);
DesiredCapabilities capabilities = DesiredCapabilities.chrome();
capabilities.setCapability(ChromeOptions.CAPABILITY, chromeOptions);
System.out.println("Driver is now ChromeDriver");
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
The footer is getting lost in this. What I am getting is:
What I am suppose to get is this:
Another code I used is:
driver.manage().window().setSize(new Dimension(1024, 786));
Can anyone please help? Thanks

Setting the size of the window wont work if you want to fit contents of a web page in window without scroll If it's a large page.
What you will have to do is adjust the zoom level to fit all contents in window.
You can do this as shown below:
WebElement html = driver.findElement(By.tagName("html"));
html.sendKeys(Keys.chord(Keys.CONTROL, Keys.SUBTRACT));
Make sure to reset the zoom level afterwards as shown below:
html.sendKeys(Keys.chord(Keys.CONTROL, "0"));
What basically happens here is the same as what happens when you press Control and - in your keyboard while focusing on your browser.
Try it out, if this serves your purpose.

You need to pass the mobileEmulation related configuration within an instance of ChromeOptions Class as follows:
Map<String, Object> deviceMetrics = new HashMap<>();
deviceMetrics.put("width", 768);
deviceMetrics.put("height", 1024);
Map<String, Object> mobileEmulation = new HashMap<>();
mobileEmulation.put("deviceMetrics", deviceMetrics);
mobileEmulation.put("userAgent", "Mozilla/5.0 (Linux; Android 4.2.1; en-us; Nexus 5 Build/JOP40D) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.166 Mobile Safari/535.19");
ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.setExperimentalOption("mobileEmulation", mobileEmulation);
WebDriver driver = new ChromeDriver(chromeOptions);
Note: Testing a mobile website on a desktop using mobile emulation can be useful, but testers should be aware that there are many subtle differences such as:
Entirely different GPU, which may lead to big performance changes;
Mobile UI is not emulated (in particular, the hiding url bar affects page height);
Disambiguation popup (where you select one of a few touch targets) is not supported;
Many hardware APIs (for example, orientationchange event) are unavailable.
Reference
Mobile Emulation
tl; dr
Mobile Emulation is subject to a known issue Test testClickElement from MobileEmulationCapabilityTest class fails on Chromium for all platforms

Related

How to click "Allow" automatically on Google Chrome pop-up using Selenium + Java

Based on what I have read, there is a way to do this for Google Chrome versions < 50 and a way to do this for Google Chrome versions > 50. I am using Google Chrome 91.
There is an answer on to this located here: How to click Allow on Show Notifications popup using Selenium Webdriver
which states that I need to do something like this:
//Create a map to store preferences
Map<String, Object> prefs = new HashMap<String, Object>();
//add key and value to map as follow to switch off browser notification
//Pass the argument 1 to allow and 2 to block
prefs.put("profile.default_content_setting_values.notifications", 2);
//Create an instance of ChromeOptions
ChromeOptions options = new ChromeOptions();
// set ExperimentalOption - prefs
options.setExperimentalOption("prefs", prefs);
//Now Pass ChromeOptions instance to ChromeDriver Constructor to initialize chrome driver which will switch off this browser notification on the chrome browser
WebDriver driver = new ChromeDriver(options);
However, this does not work for me. This is what the pop up looks like
and this is how I am using it:
// Create a map to store preferences (to disable pop-up notifications)
Map<String, Object> prefs = new HashMap<String, Object>();
// add key and value to map as follow to switch off browser notification
// Pass the argument 1 to allow and 2 to block
prefs.put("profile.default_content_setting_values.notifications", 2);
// for local automated testing
this.chromeOptions = new ChromeOptions();
chromeOptions.setExperimentalOption("prefs", prefs);
chromeOptions.addArguments("--disable-notifications");
chromeOptions.addArguments("start-maximized");
String chromeDriverPath = "resources/chromedriver-91.exe";
System.setProperty("webdriver.chrome.driver", chromeDriverPath);
this.driver = new ChromeDriver(chromeOptions);
System.out.println("new chrome driver started.....");
this.driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
So as you can see, I have tried multiple different ways. "--disable-notifications" did not work and neither did chromeOptions.setExperimentalOption("prefs", prefs);
When I run my program, the pop-up is still there, I need to Selenium to click "Allow" on the pop-up so I can continue with the rest of the program.
You are trying to download a file, which is different behavior than showing notifications. Try
prefs.put("profile.default_content_setting_values.automatic_downloads", 1);

Chrome profile to disable "Know your location" pop up

I am running my tests in Google Chrome using chromedriver.exe binary. At one particular page this pop up comes which doesn't intervene/effect with the test but client doesn't want to see it. Possible reason could be, at the failure of test case it will capture the screenshot along with this pop up.
How can I create a chrome profile or capabilities which would disable this pop up?
Something like this:
ChromeOptions options = new ChromeOptions();
options.addArguments("user-data-dir=C:/Users/user_name/AppData/Local/Google/Chrome/User Data");
Edit:
This code stopped the "Know your location" pop up to come but generated another pop up. So its only partially working.
options.addArguments("--enable-strict-powerful-feature-restrictions");
driver = new ChromeDriver(options);
Use --disable-geolocation, Chrome Options as given below:
options.addArguments("--disable-geolocation");
Also list of chrome command-line switches can be found in the below link:
http://peter.sh/experiments/chromium-command-line-switches/
Declaring in the following way worked for me.
// Declare variables
ChromeOptions options = new ChromeOptions();
Map<String, Object> prefs = new HashMap<String, Object>();
Map<String, Object> profile = new HashMap<String, Object>();
Map<String, Object> contentSettings = new HashMap<String, Object>();
// Specify the ChromeOption we need to set
contentSettings.put(“geolocation”, 1);
profile.put(“managed_default_content_settings”, contentSettings);
prefs.put(“profile”, profile);
options.setExperimentalOption(“prefs”, prefs);
// Declare the capability for ChromeOptions
caps.setCapability(ChromeOptions.CAPABILITY, options);
This code solved my problem with geolocation
options.AddUserProfilePreference("profile.default_content_setting_values.geolocation", 2);
The --disable-geolocation flag didn't do anything for me.
I am also running with incognito on, so that might be affecting some things.
I can confirm that the following python selenium code will disable the location popup
prefs = {
"profile.default_content_setting_values.geolocation": 2,
}
options.add_experimental_option("prefs", prefs)
In the interest of digging deeper.
If you need to change any setting. It can be done by comparing the "${PROFILE}Preferences" file that is saved
I'd recommend always starting with a clean profile as follows, then setting whatever preferences you want in code. to get a reproducible result.
data_dir = "tmp/remote-profile"
if os.path.exists(data_dir):
shutil.rmtree(data_dir)
options.add_argument("--user-data-dir=tmp/remote-profile")
options.add_argument('--profile-directory=Default')
In the case above the Preferences file will be in tmp/remote-profile/Default/Preferences
Add this below command line argument, which will restrict geolocation feature.
String url = "http://ctrlq.org/maps/where/";
//Chromedriver Version : 2.19.346078
System.setProperty("webdriver.chrome.driver", "CHROMEDRIVERPATH");
ChromeOptions options = new ChromeOptions();
options.addArguments("--start-maximized");
options.addArguments("--enable-strict-powerful-feature-restrictions");
WebDriver driver = new ChromeDriver(options);
driver.get(url);
And other way is after lauching the chrome browser, Through the selenium code implement below steps which will disable the geo location popup.
Go to : chrome://settings/content
Under the location select 'Do not allow any site to track your physical location' option.
Click On Done

how to change file download location in Webdriver while using chrome driver/firefox driver

I am trying to save an image by using save as option inside a specific folder. I found a way by which I am able to right click on the image which I want to save using save as option. But the problem where I am stuck is after getting the os window which asks where to save the file I am not able to send the desired location because I don't know how to do it. I went through the similar questions asked on this forum but non of them helped so far.
Code is-
For Firefox-
public class practice {
public void pic() throws AWTException{
WebDriver driver;
//Proxy Setting
FirefoxProfile profile = new FirefoxProfile();
profile.setAssumeUntrustedCertificateIssuer(false);
profile.setEnableNativeEvents(false);
profile.setPreference("network.proxy.type", 1);
profile.setPreference("network.proxy.http", "localHost");
profile.setPreference("newtwork.proxy.http_port",3128);
//Download setting
profile.setPreference("browser.download.folderlist", 2);
profile.setPreference("browser.helperapps.neverAsk.saveToDisk","jpeg");
profile.setPreference("browser.download.dir", "C:\\Users\\Admin\\Desktop\\ScreenShot\\pic.jpeg");
driver = new FirefoxDriver(profile);
driver.navigate().to("http://stackoverflow.com/users/2675355/shantanu");
driver.findElement(By.xpath("//*[#id='large-user-info']/div[1]/div[1]/a/div/img"));
Actions action = new Actions(driver);
action.moveToElement(driver.findElement(By.xpath("//*[#id='large-user-info']/div[1]/div[1]/a/div/img"))).perform();
action.contextClick().perform();
Robot robo = new Robot();
robo.keyPress(KeyEvent.VK_V);
robo.keyRelease(KeyEvent.VK_V);
// Here I am getting the os window but don't know how to send the desired location
}//method
}//class
For chrome-
public class practice {
public void s() throws AWTException{
WebDriver driver;
System.setProperty("webdriver.chrome.driver","C:\\Users\\Admin\\Desktop\\chromedriver.exe");
driver = new ChromeDriver();
driver.navigate().to("http://stackoverflow.com/users/2675355/shantanu");
driver.findElement(By.xpath("//*[#id='large-user-info']/div[1]/div[1]/a/div/img"));
Actions action = new Actions(driver);
action.moveToElement(driver.findElement(By.xpath("//*[#id='large-user-info']/div[1]/div[1]/a/div/img"))).perform();
action.contextClick().perform();
Robot robo = new Robot();
robo.keyPress(KeyEvent.VK_V);
robo.keyRelease(KeyEvent.VK_V);
// Here I am getting the os window but don't know how to send the desired location
}
}
There are two things that are going wrong in code.
For Firefox:
You need to set
profile.setPreference("browser.download.dir", "C:\\Users\\Admin\\Desktop\\ScreenShot\\");
not to
profile.setPreference("browser.download.dir", "C:\\Users\\Admin\\Desktop\\ScreenShot\\pic.jpeg");
secondly, you are setting preference browser.download.folderlist, it is browser.download.folderList (L caps in folderList).
Once you have achieved this both, you can use then your Robot class to perform desired operations.
For Chromedriver try out with:
String downloadFilepath = "/path/to/download";
HashMap<String, Object> chromePrefs = new HashMap<String, Object>();
chromePrefs.put("profile.default_content_settings.popups", 0);
chromePrefs.put("download.default_directory", downloadFilepath);
ChromeOptions options = new ChromeOptions();
options.setExperimentalOption("prefs", chromePrefs);
DesiredCapabilities cap = DesiredCapabilities.chrome();
cap.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
cap.setCapability(ChromeOptions.CAPABILITY, options);
WebDriver driver = new ChromeDriver(cap);
Hope this helps. :)
For Chrome Browser:
Even you can disable the windows dialogue (Save As Dialogue) with the following code snippet. You need to do following settins in the chromedriver preferences:
turn off the download prompt if it appears
set the default directory to download the file
If PDF view plugin is enabled which opens the PDF file in browser, you can disable that so that download can start automatically
Accept any certificate in browser
String downloadFilepath = "/path/to/download/directory/";
Map<String, Object> preferences = new Hashtable<String, Object>();
preferences.put("profile.default_content_settings.popups", 0);
preferences.put("download.prompt_for_download", "false");
preferences.put("download.default_directory", downloadFilepath);
// disable flash and the PDF viewer
preferences.put("plugins.plugins_disabled", new String[]{
"Adobe Flash Player", "Chrome PDF Viewer"});
ChromeOptions options = new ChromeOptions();
options.setExperimentalOption("prefs", preferences);
DesiredCapabilities capabilities = DesiredCapabilities.chrome();
capabilities.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
capabilities.setCapability(ChromeOptions.CAPABILITY, options);
driver = new ChromeDriver(capabilities);
I spent a lot of time to investigate how to download pdf file in firefox browser without Save As popup appearance. It migth be help someone.
After some local investigation, how to download pdf file in firefox without any Save As popup, I found the minimum required preference in firefox profile:
profile.setPreference("pdfjs.disabled", true);
profile.setPreference("browser.helperApps.neverAsk.saveToDisk", "application/pdf");
Of course you can add some additional preferences.
It works in Firefox 45-46 versions.
You partially answered your own question:
the problem where i am stuck is after getting the os window
Selenium is a browser automation tool - os window is not a browser! You will need to use something else. There are many choices, depending on your needs: Sikuli, Robot, AutoIt, ...
Use the same Robot class and press enter to select the "Save" in the Windows dialog box.
robo.keyPress(KeyEvent.VK_ENTER);
robo.keyRelease(KeyEvent.VK_ENTER);
if you need to rename it copy the file name in the clipboard and pass like below
StringSelection file = new StringSelection("D:\\image.jpg");
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(file, null);
Robot rb = new Robot();
rb.setAutoDelay(2000); // Similar to thread.sleep
rb.keyPress(KeyEvent.VK_CONTROL);
rb.keyPress(KeyEvent.VK_V);
rb.keyRelease(KeyEvent.VK_CONTROL);
rb.keyRelease(KeyEvent.VK_V);
rb.setAutoDelay(2000);
rb.keyPress(KeyEvent.VK_ENTER);
rb.keyRelease(KeyEvent.VK_ENTER);
Probably not the best solution but you could try using sikuli api to confirm the save for the box that shows up.
The save as box is an OS window.
For Chrome, it will works
String downloadFilepath = "/path/to/download";
HashMap<String, Object> chromePrefs = new HashMap<String, Object>();
chromePrefs.put("profile.default_content_settings.popups", 0);
chromePrefs.put("download.default_directory", downloadFilepath);
ChromeOptions options = new ChromeOptions();
options.setExperimentalOption("prefs", chromePrefs);
WebDriver driver = new ChromeDriver(options);

Does ChromeDriver support Rotatable for mobileEmulation

I'm testing a web app with Selenium 2.44 and ChromeDriver 2.13. I'm using Chromes mobile emulation to mock connecting from a mobile device. I need to change the screen orientation mid test from portrait to landscape and I can't seem to get it working.
Sample code for trying to augment WebDriver to Rotatable is below but it is throwing a ClassCastException when trying to cast to Rotatable. Can someone tell me if I am doing something wrong or if ChromeDriver does not support rotation?
package test;
import org.openqa.selenium.Rotatable;
import org.openqa.selenium.ScreenOrientation;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.remote.AddRotatable;
import org.openqa.selenium.remote.Augmenter;
import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.remote.DesiredCapabilities;
import java.util.HashMap;
import java.util.Map;
public class Main {
public static void main(String[] args) {
System.setProperty(
"webdriver.chrome.driver",
"Path/To/chromedriver.exe"
);
Map<String, String> mobileEmulation = new HashMap<>();
mobileEmulation.put("deviceName", "Google Nexus 4");
Map<String, Object> chromeOptions = new HashMap<>();
chromeOptions.put("mobileEmulation", mobileEmulation);
DesiredCapabilities capabilities = DesiredCapabilities.chrome();
capabilities.setCapability(ChromeOptions.CAPABILITY, chromeOptions);
capabilities.setCapability(CapabilityType.ROTATABLE, true);
WebDriver driver = new ChromeDriver(capabilities);
driver.get("http://m.rte.ie");
// Try and rotate
Augmenter augmenter = new Augmenter();
augmenter.addDriverAugmentation(CapabilityType.ROTATABLE, new AddRotatable());
WebDriver augmentedDriver = augmenter.augment(driver);
ScreenOrientation currentOrientation = ((Rotatable) augmentedDriver).getOrientation();
System.out.println(String.format("Current Orientation is: %s", currentOrientation));
driver.quit();
}
}
It appears as though Chrome supports switch orientation as is documented here: (https://developer.chrome.com/devtools/docs/device-mode) if you look at the section on, 'Swap dimensions'. I have tried this manually in the browser and it works fine. Just wondering if ChromeDriver does not support the Rotatable interface, is there a way to update the screen dimensions on the fly?
It was a tough one. Hope this saves a decent amount of effort for someone. As for now, ChromeDriver only supports portrait orientation in mobile emulation mode. There are no workarounds whatsoever to pass it as an option and no ability to trigger from javascript either.
Yet, there is a solution that seems to work for me. What you need to do is simply start the ChromeDriver with userAgent option which represents your device. For instance, here is what it looks like for iPad emulation:
Map<String, Object> mobileEmulation = new HashMap<>();
String userAgent = "Mozilla/5.0 (iPad; U; CPU OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 " +
"(KHTML, like Gecko) Version/4.0.4 Mobile/7B334b Safari/531.21.10";
ChromeOptions options = new ChromeOptions();
options.addArguments("--user-agent=" + userAgent);
options.addArguments("window-size=1039,859");
DesiredCapabilities capabilities = DesiredCapabilities.chrome();
capabilities.setCapability(ChromeOptions.CAPABILITY, options);
Also, you might want to set the dimensions that resemble the emulated device. It's a bit tricky, since only the window size could be set in ChromeOptions. And again, with the use of this tool: Chrome viewport dimensions plugin you can find the correct ratio for your resolution. In my case, viewport's 1024x768 correspond to 1039x859 of window-size.
P.S. it could be done only on driver start. There is no possibility to change the orientation on the fly
it seems that it accepts "deviceOrientation" as a capacity with values "portrait" and "landscape", but unfortunately this is not yet implemented.
Waiting for the same answer.

Selenium 2 chrome driver preferences java equivalent to RubyBindings

I've been looking for a way to set the driver preferences for chrome driver using java for the past two days with no luck.
I have however found a solution in ruby VIA RubyBindings and would like to know if there is a java equivalent line I can use for this.
The ruby code is the following:
profile = Selenium::WebDriver::Chrome::Profile.new
profile['download.prompt_for_download'] = false
profile['download.default_directory'] = "/path/to/dir"
driver = Selenium::WebDriver.for :chrome, :profile => profile
While searching I found that chrome does not have a profiler I could use like the FirefoxProfile class, so I started using the DesireCapabilities class instead. After further investigation into this problem I found that I could set the "switches" and "prefs" VIA capabilities.setCapabilitiy and ended up with the following:
Map<String, String> prefs = new Hashtable<String, String>();
prefs.put("download.prompt_for_download", "false");
prefs.put("download.default_directory", "/path/to/dir");
prefs.put("download.extensions_to_open", "pdf");
DesiredCapabilities capabilities = DesiredCapabilities.chrome();
capabilities.setCapability("chrome.prefs", prefs);
dr = new ChromeDriver(capabilities);
However I was not able to get this working, the default download directory was never changed to the specified directory once started. I am unsure if there is a problem with how I am trying to set this capability or if the problem lies elsewhere.
In the end I eventually used the solution proposed here:
http://dkage.wordpress.com/2012/03/10/mid-air-trick-make-selenium-download-files/
but I would like to know if it is possible to do this more cleanly but just setting the preferences directly instead of using the UI
Any help is appreciated, Thanks!
Update:
Surprisingly after updating Selenium 2 to version 2.24.1 (and to windows chrome 22), the code above with the Maps work as expected, the only problem now is that they deprecated the the use of the constructor ChromeDriver(DesiredCapabilities capabilities), and instead recommend I use the ChromeOptions class, which I cannot get working for the above scenario.
Below is the wiki page explaining the use of both ChromeOptions and DesiredCapabilities:
http://code.google.com/p/chromedriver/wiki/CapabilitiesAndSwitches
The Ruby bindings actually expands that to:
{
"download": {
"prompt_for_download": false,
"default_directory": "/path/to/dir"
}
}
Try building your Java prefs object like that and see if it works. The string vs boolean false could also be an issue.
Try this (Forgive my java which is quite rusty, but hopefully you get the idea)
Dictionary download = new Dictionary();
download["default_directory"] = "/path/to/dir";
Dictionary prefs = new Dictionary();
prefs["browser"] = download;
DesiredCapabilities capabilities = DesiredCapabilities.chrome();
capabilities.setCapability("chrome.prefs", prefs);
WebDriver driver = new ChromeDriver(capabilities);
Update: I just browsed the code and it seems that what I suggested above probably won't work. The ruby chrome profile class creates zip file with chrome profile file structure in it to support chrome preference. I couldn't find such facility code in java. There is a Firefox profile in java that does the simliar thing for firefox, but obviously that won't work for chrome. So in short, this feature is not supported yet in java.
Newer versions (I tested Chrome 44.0.2403.125, Selenium 2.47.1, and ChromeDriver 2.17.340128) work with the following:
ChromeOptions options = new ChromeOptions();
Map<String, Object> prefs = new HashMap<String, Object>();
prefs.put("download.default_directory", "/path/to/directory");
options.setExperimentalOption("prefs", prefs);
ChromeDriver chromeDriver = new ChromeDriver(options);

Categories