Unable to Download csv file using werbdriver + java - selenium-webdriver

I need to downlond csv file from my application. In my application there is table which contains rows and on right click of that row it display download option , on click on of that download it displays windows popup with open and save button.
To download csv from my application i have written below code but which is not working :(
WebDriver driver;
FirefoxProfile profile = new FirefoxProfile();
profile.setPreference("browser.download.dir", "c:\\test");
profile.setPreference("browser.download.folderList", 2);
profile.setPreference("browser.helperApps.neverAsk.saveToDisk","text/csv");
profile.setPreference("browser.download.useDownloadDir", false);
profile.setPreference("browser.download.manager.showWhenStarting", false);
driver = new FirefoxDriver(profile);
driver.get("Application link");
// Steps to click on Download file
Please Help.![enter image description here][1]

Try adding
profile.setPreference("browser.download.downloadDir", "c:\\test");
profile.setPreference("browser.download.defaultFolder", "c:\\test");
In addition - csv can come in many content types, not just text/csv..
Try using Firefox addon like HTTP headers to see the exact type the response.

Related

File upload functionality of Selenium web driver for non-input button without AutoIt or Skuliii

I need to upload a document via Selenium WebDriver using Chromedriver. I have tried all the Action class and JavaScript stuff, but those do not work. I am assuming they do not work because those are relying on the button to be an input field, however, the upload button I'm dealing with is not. It's HTML looks like this:
Steps to reproduce:
Go to: https://www.fedex.com/apps/printonline/#!
Click on View Products under Marketing Material
Click on Get Started under Brochure
Click on Use your File to upload the file
Use Your File
I am able to click the use your file button, but I am not sure how I can upload the file.
driver.get("https://www.fedex.com/apps/printonline/#!");
driver.manage().window().maximize();
driver.manage().deleteAllCookies();
driver.manage().timeouts().pageLoadTimeout(40, TimeUnit.SECONDS);
driver.manage().timeouts().implicitlyWait(30,TimeUnit.SECONDS);
//Thread.sleep(6000);
if (driver.findElement(By.xpath("//area[#alt='close']")) != null) {
driver.findElement(By.xpath("//area[#alt='close']")).click();
}
driver.findElement(By.xpath("//a[#title='Marketing Materials']/child::button")).click();
Thread.sleep(1000);
driver.findElement(By.xpath("//a[#title='Get Started - Brochures']")).click();
Thread.sleep(1000);
WebElement element = driver.findElement(By.xpath("//*[#class='btn fxg-btn-orange mycomputer-upload-link']"));
((JavascriptExecutor)driver).executeScript("arguments[0].click()", element);
Ok so first of all get rid of those Thread.sleep(), use fluent wait with polling time, preferably as a function to locate the elements:
private WebElement waitFor(By locator) {
int timeout = 10;
FluentWait<WebDriver> wait = new FluentWait<>(driver)
.pollingEvery(Duration.ofMillis(200))
.withTimeout(Duration.ofSeconds(timeout))
.ignoring(NoSuchElementException.class);
return wait.until((driver) -> driver.findElement(locator));
}
Then you can click the buttons and upload the file like this:
waitFor(By.cssSelector("button.view-products")).click();
waitFor(By.cssSelector("a.get-started")).click();
waitFor(By.cssSelector("a.get-started")).click();
waitFor(By.cssSelector("input.file-upload")).sendKeys("path_to_my_file");
Notice I am using the input element to upload the file - I am not clicking the a link, as you do not need to do that. Just send the path directly to the input element.

Handle browser dialog window without focus

I have a Selenium WebDriver based script to automate file uploading. It uploads list of files one by one. I use AutoIT script to handle dialog window, file chooser window. Parameter $CmdLine[1] contains the path of actual file.
ControlFocus("Open a file","","Edit1")
ControlSetText("Open a file","","Edit1", $CmdLine[1])
ControlClick("Open a file","","Button1")
I execute it from Java code as following:
Runtime.getRuntime().exec(autoITExecutable);
It opens dialog window, so it can't work without focus on browser window.
File upload field works like this demo:
https://encodable.com/uploaddemo/
I ran simple script for the link you gave and it works great
import os
from selenium import webdriver
driver = webdriver.Chrome()
driver.get("https://encodable.com/uploaddemo/")
driver.find_element_by_name("uploadname1").send_keys(os.getcwd() + "/test.csv")
driver.find_element_by_name("email_address").send_keys("none#getnada.com")
driver.find_element_by_name("first_name").send_keys("Tarun")
driver.find_element_by_id("uploadbutton").click()
Try your code in similar format as shown below and try:
WinWaitActive("File Upload") // enter the title of the pop up
Send("Path of the file to enter") // enter the path of the file to upload
Send("{ENTER}") / press enter

Unable to Download file using selenium webdriver

Hi i want to download a file i wrote this code but while executing the file is not getting downloaded its coming up to the dialog box. please suggest
FirefoxProfile fprofile=new FirefoxProfile();
fprofile.setPreference("browser.download.dir", "D:\\Webdriver_download");
fprofile.setPreference("browser.download.folderlist", 2);
fprofile.setPreference("browser.helperApps.neverAsk.saveToDisk", "text/csv, application/pdf, application/x-msexcel,application/excel,application/x-excel,application/excel,application/x-excel,application/excel, application/vnd.ms- excel,application/x-excel,application/x-msexcel,image/png,image/jpeg,text/html,text/plain,application/msword,application/xml,application/excel,text/x-c");
fprofile.setPreference("browser.download.manager.showWhenStarting", false);
WebDriver driver=new FirefoxDriver(fprofile);
driver.get("http://spreadsheetpage.com/index.php/file/C35/P10/");
driver.manage().window().maximize();
driver.findElement(By.linkText("smilechart.xls")).click();
You are doing two things wrong here:
Firstly:
browser.download.folderlist has folderList (i.e. L is capital in list), keeping previous string will download it to downloads folder instead of your desired folder.
Secondly:
browser.helperApps.neverAsk.saveToDisk you have set application/vnd.ms- excel, it is application/vnd.ms-excel without space.
Hope this helps.

How to take full page screen shot in internet explorer using selenium webdrivers

I am not able to take the whole page screen shot using selenium webdriver.I am using internet explorer.
I tried robot function of java using mouse roll button but failed.
Please try the following let me know if it works for you
WebDriver driver = new FirefoxDriver();
driver.get("http://www.somewebsite.com/");
File imgFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(imgFile , new File("c:\\tmp\\test.png"));
if i have misunderstood you que please let me know
If the above answer fails, you can give a try making using of Augemented WebDriver, which can be used with IEDriver on it's latest version, try following code
WebDriver augmentedDriver = new Augmenter().augment(driver);
File screenFile = ((TakesScreenshot) augmentedDriver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(screenFile.getAbsolutePath(), new File("c:\\tmp\\test.png"));
You can also get screenshot in the form of bytes, by switching the OutputType as required
.getScreenshotAs(OutputType.BYTES)

cookies validation using selenium

I am new to selenium. Actually I am working on some cookie validation project, which requires me to manually check the cookies present before and after clicking on some consent link in multiple browsers (Firefox, ie, chrome, safari).
Previously in the phase 1 project I ran a qtp script to treat the firefox as a window object and capture screenshots, but that is quite troublesome if the resolution changes or any minor look-n-feel changes. Also it is quite difficult to manage and it works on firefox only and I needed to write the same script again for chrome and safari. Apart from this since QTP is licensed product and currently we are using seat license so I can't run it on multiple machines to speed up execution.
So I thought moving to Selenium. As of now my requirement is:
1. open the page - take the screenshot once page loaded.
2. check the cookies using firebug or any other way - take the screenshot
3. click the link to close the consent - take screenshot once consent closed.
4. refresh the page and again check the cookies using firebug - take screenshot
So I done some research on selenium and found that I can validate the cookies using verifyCookie but still I need screenshot of firebug window for cookies. So I got stuck here.
please help me out here..
I found some possible way to do this on Firefox but now I was looking forward for something similar for Chrome if that possible. Thanks
Selenium cannot interact with firefox extensions, or the browser in the way you want it to.
What you can do is collect a list of cookies on the page by doing:
driver.manage().getCookies()
This will give you a list of all cookies that are visible to Selenium. Please note that this is the same as the cookies that are visible in the JavaScript console (Not all cookies are visible via JavaScript, for example cookies set with the HTTPOnly attribute) using:
document.cookie
I would suggest you use getCookies() to programatically validate the cookies.
In selenium IDE if you want to take screenshot of the page use captureEntirePageScreenshot command
captureEntirePageScreenshot | D:\\test.png |
D:\\test.png - path of file where you want to save the file
Got some solution
public class Selenium1st {
/**
* #param args
*/
public static void main(String[] args) throws IOException, AWTException{
// TODO Auto-generated method stub
System.setProperty("webdriver.firefox.bin","C:\\Program Files (x86)\\Mozilla Firefox\\Firefox.exe");
FirefoxProfile firefoxProfile = new FirefoxProfile();
String domain = "extensions.firebug.";
firefoxProfile.setPreference("app.update.enabled", false);
firefoxProfile.addExtension(new File("E:\\softs\\selenium-2.29.0\\firebug\\firebug-1.11.2-fx.xpi"));
firefoxProfile.setPreference(domain + "currentVersion", "1.11.2");
firefoxProfile.setPreference("extensions.firebug.cookies.enableSites", true);
firefoxProfile.setPreference("extensions.firebug.allPagesActivation", "on");
firefoxProfile.setPreference(domain + "framePosition", "bottom");
firefoxProfile.setPreference(domain + "defaultPanelName", "cookies");
WebDriver driver = new FirefoxDriver(firefoxProfile);
driver.get("http://www.google.com/webhp?complete=1&hl=en");
WebElement query = driver.findElement(By.name("q"));
query.sendKeys("Cheese");
query.sendKeys("\n");
Robot robot = new Robot();
BufferedImage img = robot.createScreenCapture(new Rectangle(new Dimension(1024, 768)));
File path = new File("E:\\abc");//Path to your file
if(path.getName().indexOf(".jpg") == -1){
path = new File(path.getPath() + ".jpg");
}
ImageIO.write(img, "jpg", path);
}
}
might be useful.

Resources