How to maximize selenium screen - java

Would anyone know how to maximize the selenium webdriver window with java and google chrome.
I already tried some commands like maximize () window () and did not work.

This is how I did it.
ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.addArguments("--start-maximized");
WebDriver driver = new ChromeDriver(chromeOptions);

Try with this:
String chromeDriver = "/PathTo/chromedriver";
System.setProperty("webdriver.chrome.driver", chromeDriver);
ChromeDriver driver = new ChromeDriver();
//set your max dimension
java.awt.Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
Dimension dim= new Dimension((int)screenSize.getWidth(),(int)screenSize.getHeight());
driver.manage().window().setSize(dim);

//Maximizing Chrome Window.
int x=1280; //according to your screen resolution
int y=860; //according to your screen resolution
JavascriptExecutor executor = (JavascriptExecutor) driver;
executor.executeScript("window.resizeTo(x, y);");

You can try too sending keystrokes:
SendKeys(Keys.ALT, " "); // Space, open window menu
SendKeys("x"); // Maximize
Include a pause between keystrokes, although it could work for you without it.

If you're using a Mac you'll need to use the following
ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.addArguments("--start-fullscreen");
WebDriver driver = new ChromeDriver(chromeOptions);

You can do this using the WebDriver API, and this will work with other browsers and RemoteWebDriver:
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
https://stackoverflow.com/a/26998387/5603509

Try following code:
ChromeOptions options = new ChromeOptions();
options.addArguments("start-maximized"); //This maximizes the window
options.setExperimentalOption("prefs", chromePrefs);
WebDriver driver = new ChromeDriver(options);

Related

Java Selenium "Element Not Interactable Exception" when using sendKeys to open multiple tabs

I am trying to web scrape a Quebec government website for law names and their associated PDFs but when I try to open the tabs of all the different laws to get their PDF links, I get an ElementNotInteractable Exception when it attempts to open the 9th link. I tried opening the link by itself and it opens fine but when it is going through all the laws, it stops there and gives me that exception. Here is my code snippet:
static SortedMap<String,String> QuebecConsolidatedStatutesAndPDFs = new TreeMap<String,String>();
public static void main(String[] args) throws InterruptedException {
System.setProperty("webdriver.chrome.driver", "C:\\WorkSpace\\Driver\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
WebDriverWait wait = new WebDriverWait(driver,Duration.ofSeconds(5000));
driver.get("http://www.legisquebec.gouv.qc.ca/en/chapters?corpus=statutes&selection=all");
Thread.sleep(5000);
List<WebElement> QuebecConsolidatedStatutes = driver.findElements(By.xpath("//body/div/div/div[2]/div/div[2]/table/tbody/tr[contains(#class, 'clickable')]/td/a"));
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
String parent = driver.getWindowHandle();
for (int i=0; i<QuebecConsolidatedStatutes.size(); i++){
String opentabs = Keys.chord(Keys.CONTROL, Keys.ENTER);
wait.until(ExpectedConditions.visibilityOf(QuebecConsolidatedStatutes.get(i)));
QuebecConsolidatedStatutes.get(i).sendKeys(opentabs);
}
There are several issues here:
The main problem is that you have to scroll the element you want to click on into the view. Your default initial screen height presents 8 rows while to click on 9-th row and more you have to scroll that element first into the view.
You could set driver window to better dimensions, this will show you more screen, however you will still have to scroll, but after 15 elements.
You should improve your locators.
You should not mix up WebDriverWait and implicitlyWait.
This should work better:
static SortedMap<String,String> QuebecConsolidatedStatutesAndPDFs = new TreeMap<String,String>();
public static void main(String[] args) throws InterruptedException {
System.setProperty("webdriver.chrome.driver", "C:\\WorkSpace\\Driver\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
WebDriverWait wait = new WebDriverWait(driver,Duration.ofSeconds(5000));
driver.manage().window().maximize();
driver.get("http://www.legisquebec.gouv.qc.ca/en/chapters?corpus=statutes&selection=all");
wait.until(ExpectedConditions.numberOfElementsToBeMoreThan(By.cssSelector("tr.clickable a"), 100));
Thread.sleep(300);
List<WebElement> QuebecConsolidatedStatutes = driver.findElements(By.cssSelector("tr.clickable a"));
String parent = driver.getWindowHandle();
for (int i=0; i<QuebecConsolidatedStatutes.size(); i++){
String opentabs = Keys.chord(Keys.CONTROL, Keys.ENTER);
((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);", QuebecConsolidatedStatutes.get(i));
Thread.sleep(300);
wait.until(ExpectedConditions.visibilityOf(QuebecConsolidatedStatutes.get(i)));
QuebecConsolidatedStatutes.get(i).sendKeys(opentabs);
}
}

Choose directory to download files with selenium in chrome

I need to download XLSX files using Java + Selenium in chrome, but I'm not able to choose the folder to download the files. I've tried all the other alternatives I found here, but from what I've noticed, all the others are already obsolete.
Here is my code:
String downloadFilepath = "D:\\down\\";
HashMap<String, Object> chromePrefs = new HashMap<String, Object>();
chromePrefs.put("profile.default_content_settings.popups", 0);
chromePrefs.put("prompt_for_download", false);
chromePrefs.put("directory_upgrade", true);
chromePrefs.put("download.default_directory", downloadFilepath);
ChromeOptions options = new ChromeOptions();
options.setExperimentalOption("prefs", chromePrefs);
options.addArguments("--disable-notifications");
DesiredCapabilities cap = DesiredCapabilities.chrome();
cap.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
cap.setCapability(ChromeOptions.CAPABILITY, options);
System.setProperty("webdriver.chrome.driver", "C:\\chromedriver.exe");
driver = new ChromeDriver(options);
I managed to resolve it. I downloaded the last stable version that came out in July (mine was from June) of chromedriver and put the code below.
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);

How to switch to a new window and print the title in selenium webdriver (without windowhandles)

Iam new to selenium and trying to switch to new amazon tab which I opened and print the title
But when Sending control and Tab nothing happens how to achieve it can anyone help here :)
WebDriverManager.chromedriver().setup();
WebDriver driver = new ChromeDriver();
driver.get("https://www.amazon.com");
//Thread.sleep(6000);
Actions a = new Actions(driver);
List<WebElement> el= driver.findElements(By.xpath("(//div[#class='navFooterColHead'])[1]/../ul/li/a"));
for(int i=0;i<el.size();++i)
{
el.get(i).sendKeys(Keys.Control,Keys.Enter);
}
driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL +"\t");

Selenium Remote WebDriver get canvas content using Chrome in headless mode

I'm trying to get Whatsapp QR with Selenium WebDriver on remote machine.
I using latest version on docker package
selenium/standalone-chrome:latest
The point is, if I try the following code without headless on, works smooth.
Maybe my configuration isnt correct.
Any ideas?
ChromeOptions dCap = new ChromeOptions();
dCap.setHeadless(true);
dCap.setCapability("platform", "LINUX");
dCap.setCapability("version", "latest");
dCap.addArguments("disable-infobars");
dCap.addArguments("--start-maximized");
dCap.addArguments("--disable-extensions");
dCap.addArguments("--disable-gpu");
dCap.addArguments("--window-size=1920x1080");
dCap.addArguments("--enable-javascript");
String driverPath = System.getProperty("user.dir") + "/exe/chromedriver";
System.setProperty("webdriver.chrome.driver", driverPath);
URL rutaProxy = new URL("http://localhost:4444/wd/hub");
WebDriver driver = new RemoteWebDriver(rutaProxy, dCap);
driver.get("https://web.whatsapp.com/");
WebDriverWait espera = new WebDriverWait(driver, 20);
espera.until(ExpectedConditions.presenceOfElementLocated(By.cssSelector(".landing-main canvas")));
WebElement canvas = driver.findElement(By.cssSelector(".landing-main canvas"));
JavascriptExecutor js = (JavascriptExecutor)driver;
String imagenBase64 = (String) js.executeScript("return arguments[0].toDataURL('image/png').substring(21);", canvas);
//TEST
byte[] imageByte = Base64.getDecoder().decode(imagenBase64.substring(1));
ByteArrayInputStream bis = new ByteArrayInputStream(imageByte);
BufferedImage image = ImageIO.read(bis);
bis.close();
File outputfile = new File("image.png");
ImageIO.write(image, "png", outputfile);
driver.close();
I've been in this situation, add more time delay between a action and a window popup, because the refresh of some DOM elements takes time. Enabling headless requires more latency than not enabling it.

Selenium does not recognize a new opened window

Hi all IM having troubles. My test click an hyperlynk and a new window is displayed. the problem is that when I implement windows handlers selenium only identify one window instead of 2 window and when I try to find the element of the window, well I cant cause for selenium the window never exist :(
driver.switchTo().frame(CQLo.getMframe());
WebElement Rad_CIT = (new WebDriverWait(driver,10)).until(ExpectedConditions.elementToBeClickable(CQLo.getRadCIT()));
Rad_CIT.click();
WebElement Text_CIT = (new WebDriverWait(driver, 10)).until(ExpectedConditions.presenceOfElementLocated(CQLo.getTextCIT()));
Text_CIT.clear();
Text_CIT.sendKeys(citbox);
setLog("CITBox: " +citbox);
//WebElement Link_WFM =
Actions act = new Actions(driver);
WebElement onElement = (new WebDriverWait(driver, 10)).until(ExpectedConditions.presenceOfElementLocated(CQLo.getLink_WFM_Admin()));
act.contextClick(onElement).perform();
act.sendKeys("o").perform();
Set <String> wind_ows = driver.getWindowHandles();
for(String sw : wind_ows)
{ System.out.println(""+sw.toString());}
setLog("Open log on " +citbox);
Thread.sleep(2000);
WebElement Text_UserN = (new WebDriverWait(driver, 10)).until(ExpectedConditions.presenceOfElementLocated(Elog.getUserName()));
Text_UserN.sendKeys(MSR_name);
WebElement Text_UserP = (new WebDriverWait(driver, 10)).until(ExpectedConditions.presenceOfElementLocated(Elog.getUserPassword()));
Text_UserP.sendKeys(MSR_pass);
WebElement B_logon = (new WebDriverWait(driver, 10)).until(ExpectedConditions.elementToBeClickable(Elog.getB_logon()));
B_logon.click();
after printing the SET with the windows I only receive one window
Wait some time before you get window handles after performing click on element. I think by the time you read driver window handles, new window might not be opened.

Categories

Resources