Finding element while using Selenium Remote Server - java

in my test I'm trying to download file from server, verify (if its downloaded) and delete it. But everytime I run my test with remote server (Selenium Grid, Chrome version=59.0.3071.115), I receive NullPointer during verification.
If I try run the test locally it passes without any problems.
My remote driver class
private WebDriver getRemoteDriver(Browser browser) throws MalformedURLException {
DesiredCapabilities desiredCapabilities = getCapabilities(browser);
desiredCapabilities.setCapability("platform", "LINUX");
LoggingPreferences logPrefs = new LoggingPreferences();
logPrefs.enable(LogType.BROWSER, Level.ALL);
desiredCapabilities.setCapability(CapabilityType.LOGGING_PREFS, logPrefs);
String downloadFilepath = System.getProperty("user.dir") + File.separator + "downloads";
HashMap<String, Object> chromePrefs = new HashMap<String, Object>();
chromePrefs.put("profile.default_content_settings.popups", 0);
chromePrefs.put("download.default_directory", downloadFilepath);
chromePrefs.put("download.directory_upgrade", true);
chromePrefs.put("download.extensions_to_open", "");
chromePrefs.put("download.prompt_for_download", false);
chromePrefs.put("plugins.always_open_pdf_externally", false);
ChromeOptions options = new ChromeOptions();
HashMap<String, Object> chromeOptionsMap = new HashMap<String, Object>();
options.setExperimentalOption("prefs", chromePrefs);
desiredCapabilities.setCapability(ChromeOptions.CAPABILITY, chromeOptionsMap);
desiredCapabilities.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
desiredCapabilities.setCapability(ChromeOptions.CAPABILITY, options);
final RemoteWebDriver remoteWebDriver = new RemoteWebDriver(new URL(remoteUrl), desiredCapabilities);
remoteWebDriver.setFileDetector(new LocalFileDetector());
return new Augmenter().augment(remoteWebDriver);
}
And part of the test looks like this: Click button to download file, wait for new file and verify it, delete file.
driver.findElement(By.xpath(".//*[#id='browseOrders:browseView:browseViewPdfExpTblLnk']/span[1]"))
.click();
File file = navigationUtil.WaitForNewFile(download_folder, ".pdf", 60);
String fname = file.getName();
logger.info(fname);
boolean success = file.exists();
Assert.assertTrue(success);
file.delete();
Im constantly getting java.lang.NullPointerException in line String fname = file.getName(); So I assume that the file is never downloaded.
Why there is a problem on remote server to find and click some elements. In this case there is menu that shows up after clicking "Gear button" and download button, but remote machine can't find the "Gear button" even when I try different ways to find it.

Related

The page I'm trying to access doesn't load when I use headless mode, but when I don't use it, it loads and performs the tests perfectly

I'm doing a test with selenium and java in eclipse, with chrome 62. And when I run it with headless mode enabled, the page I'm trying to access doesn't load. And if I don't activate it, yes it does.
Map<String, Object> prefs = new HashMap<String, Object>();
ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.setBinary(BINARY_PATH);
WebDriverManager.chromedriver().browserVersion("62").driverVersion("2.35").cachePath(EXECUTION_PATH).setup();
chromeOptions.setAcceptInsecureCerts(true);
chromeOptions.setHeadless(true);
prefs.put("profile.default_content_settings.popups", 0);
DriverFactory driverFactory = DriverFactory.getInstance();
driverFactory.setDownloadPath(
EXECUTION_PATH + Thread.currentThread().getName() + System.getProperty("file.separator"));
prefs.put("download.default_directory", driverFactory.getDownloadPath());
prefs.put("download.prompt_for_download", false);
chromeOptions.setExperimentalOption("prefs", prefs);
driver = new ChromeDriver(chromeOptions);

Unable to run the test scripts using Chrome Driver though am able to hit the browser with Driver.get("url")

My below code is giving expected result to hit chrome browser with the url and maximize the window.But after that it should go my my test scripts where is have login page and it is doing nothing over there
Please suggest
#BeforeClass
public void beforeClass() {
System.setProperty("webdriver.chrome.driver", "D:\\Selenium\\NCRExecutableWorkSpace\\automation-ncr\\Drivers\\chromedriver.exe");
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("profile.default_content_setting_values.notifications", 2);
ChromeOptions options = new ChromeOptions();
options.setExperimentalOption("prefs", map);
WebDriver driver = new ChromeDriver(options);
driver.manage().window().maximize();
driver.get("https://google.com");

How to download a file from a website in a specific folder, I am using Chorme

I'm trying to download a file from a website that has to be saved in a specific folder. Website http://bookboon.com/en/basics-of-accounting-information-processing-ebook
When I click on download it saves the file in the download section, I also tried to change the download directory in chrome settings, it doesn't work. I am trying automation (selenium, java). Is there any way?
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "C:\\Users\\User_2\\Downloads\\chromedriver_win32\\chromedriver.exe");
d = new ChromeDriver();
d.get("http://bookboon.com/en/basics-of-accounting-information-processing-ebook");
d.findElement(By.id("email")).sendKeys("asd#ymail.com");
WebElement One=d.findElement(By.xpath("html/body/div[1]/div/article/div/section[1]/form/div[2]/div[2]/div[1]/input"));
One.sendKeys("Studying");
One.sendKeys(Keys.TAB);
WebElement Two=d.findElement(By.xpath("html/body/div[1]/div/article/div/section[1]/form/div[2]/div[2]/div[2]/input"));
Two.sendKeys("Engineer/Science MSc");
Two.sendKeys(Keys.TAB);
WebElement Three=d.findElement(By.xpath("html/body/div[1]/div/article/div/section[1]/form/div[2]/div[2]/div[3]/input"));
Three.sendKeys("All India Institute of Medical Sciences (AIIMS), Delhi");
Three.sendKeys(Keys.TAB);
d.navigate().back();
downlinks = d.findElements(By.className("pdf"));
}
}
For Chromedriver It will work
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);
For Firefox: You need to setPreference
profile.setPreference("browser.download.dir", "Filepath");
Hope this helps. :)

Disable Chrome notifications (Selenium)

I just want to disable Chrome notifications in the Chrome opened by a Selenium Java application. (using java code)
Notifications like this one:
The problem is that settings manually set are lost after browser's window is closed.
you can use:
chrome_options = Options()
chrome_options.add_argument("--disable-notifications")
browser = webdriver.Chrome(chrome_options=chrome_options)
This question was answered in the: "chromedriver-users" google forum.
This is the working answer:
Map<String, Object> prefs = new HashMap<String, Object>();
prefs.put("profile.default_content_setting_values.notifications", 2);
ChromeOptions options = new ChromeOptions();
options.setExperimentalOption("prefs", prefs);
WebDriver driver = new ChromeDriver(options);
ChromeOptions ops = new ChromeOptions();
ops.addArguments("--disable-notifications");
System.setProperty("webdriver.chrome.driver", "./lib/chromedriver");
driver = new ChromeDriver(ops);
Someone needs this for Capybara or Watir, you can pass the --disable-notifications as an argument like "--start-fullscreen", "--disable-infobars". The following workes:
Capybara.register_driver :chrome do |app|
args = ["--disable-notifications"]
Capybara::Selenium::Driver.new(app, {:browser => :chrome, :args => args})
end
public class MultipleWindowHandle
{
public static void main(String[] args)
{
System.setProperty("webdriver.chrome.driver", "E:\\NEWSEL\\chromedriver.exe");
// Create object of HashMap Class as shown below.
Map<String, Object> prefs = new HashMap<String, Object>();
// Set the notification setting it will override the default setting.
prefs.put("profile.default_content_setting_values.notifications", 2);
// Create object of ChromeOption class.
ChromeOptions Roptions = new ChromeOptions();
// Set the experimental option.
Roptions.setExperimentalOption("prefs", prefs);
// Open chrome browser.
ChromeDriver driver = new ChromeDriver(Roptions);
driver.get("https://my.monsterindia.com/login.html");
Set<String> id = driver.getWindowHandles();
Object[] data = id.toArray();
driver.switchTo().window((String)data[1]); driver.close();
}
}

Selenium 2.0 Robot class on remote host

I just write a test which is supposed to download pdf files via webApp(Yep, I know, I should not do it on selenium, but You know, Orders.)
What do I need?
For diffrent scenarios I have to download difrent pdf, rename it and place to custom catalog. So, I have to handle with system modal window.
Everything works great, so test is run on remote host, and when I click to download the file I handle the system modal window(I used robotil package, it is extended robot class which allow us use robot class on remote host) so I use robotil class to type path to file, and file name on system modal and then click "Enter" to confirm and save the file. This is everything I need and it works, so where is the problem? here: SOMEONE should be logged to remote host, if Im logged via rdp and looks at screen(and doing my stuff on my host) then everything is great, but for the case when no one is logged, it looks like that during tests webbrowswer do not have a FOCUS, so everytime robotil class do some action this action is not focused on webbroswer(as it should).
test class:
#Test
public void compareDeposits() throws Exception {
HomePage homePage = new HomePage(driver);
PageFactory.initElements(driver, homePage);
PrintDepositsPage printDepositsPage = (PrintDepositsPage) homePage.openViaUrl(Data.baseUrl).openViewViaTopMenu(
ETopMenuItem.PrintDeposits);
((PrintDepositsPage) printDepositsPage).goToPrintedDepositsTab();
printDepositsPage.getPrintedDepositsDateRangeFromInput().click();
printDepositsPage.getPrintedDepositsDateRangeFromInput().clear();
printDepositsPage.getPrintedDepositsGoButton().click();
printDepositsPage.getFirstRecordOnPrintedDepositsTab().click();
handler.getRobot().mouseClick(371, 274, InputEvent.BUTTON1_MASK);// get focus
printDepositsPage.getPrintButtonEnabled().click();
handler.downloadFile("DepositTest");
handler object declaration:
class SystemModalWindowHandler {
private RemoteWebDriver driver;
private Date date = new Date();
private DateFormat dateFormat = new SimpleDateFormat("yyy/mm/dd");
private String extendedTestName = dateFormat.format(date).replace("/", ".") + ".pdf";
private Robotil robotil = new Robotil("xxxxx", 6667);
public Robotil getRobot(){
return robotil;
}
public void downloadFile(String testFileName) throws AWTException, InterruptedException {
boolean continueBool = true;
while (continueBool) {
String pathToTestFile = new String("C:\\DiffPdfData\\" + testFileName + "\\"
+ extendedTestName);
Thread.sleep(3000);
for (int i = 0; i < pathToTestFile.length(); i++) {
System.out.println(KeyStroke.getKeyStroke(pathToTestFile.charAt(i)) + " = "
+ (int) pathToTestFile.charAt(i));
if ((int) pathToTestFile.charAt(i) == 58) {
robotil.pressKey(KeyEvent.VK_SHIFT);
robotil.pressAndReleaseKey(KeyEvent.VK_SEMICOLON);
robotil.releaseKey(KeyEvent.VK_SHIFT);
}
else {
robotil.pressAndReleaseKey(KeyEvent.getExtendedKeyCodeForChar((int) pathToTestFile.charAt(i)));
}
}
robotil.pressAndReleaseKey(KeyEvent.VK_ENTER);
continueBool = false;
}
is there any way to get focus on webbrowser when no one is logged in?.
I believe that using the mentioned strategy you won't be able to accomplish it without logged-in user. So I suggest you to use a simpler solution.
You can configure Firefox the directly download the files - File types and download actions
If you don't want to hardcode the setting for your browser, you can setup a specific FF profile only for your tests, where you can configure where you want the files to be downloaded.
FirefoxProfile firefoxProfile = new FirefoxProfile();
firefoxProfile.setPreference("browser.download.folderList",2);
firefoxProfile.setPreference("browser.download.manager.showWhenStarting",false);
firefoxProfile.setPreference("browser.download.dir","c:\\downloads");
firefoxProfile.setPreference("browser.helperApps.neverAsk.saveToDisk","text/csv");
WebDriver driver = new FirefoxDriver(firefoxProfile);
Chrome Driver:
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);

Categories