Unable to Download file using selenium webdriver - 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.

Related

Jmeter WebDriverSampler fail with Chromedriver headless

I have some tests with WebDriverSampler in Jmeter that work correctly with chromedriver. It is a selenium script that opens a web page and checks that it contains a series of elements. Everything works right until I've tried with the chromedriver headless option.
In this case I get the exception "Expected condition failed: waiting for presence of element located by: By.xpath: ..." as if that element did not exist yet to be loaded. I do not know what can happen, because if I stop using the headless option, if everything works correctly and find the element that really exists.
This is an example of code used(it works without the headless option):
var wait = new support_ui.WebDriverWait(WDS.browser, 30);
var conditions = org.openqa.selenium.support.ui.ExpectedConditions
WDS.sampleResult.sampleStart();
WDS.sampleResult.getLatency();
WDS.browser.get('http://mi-app/');
try{
wait.until(conditions.presenceOfElementLocated(pkg.By.xpath('/ruta_de elemento_existente')));
WDS.log.info('OK')
}catch(e){
WDS.sampleResult.setSuccessful(false);
WDS.sampleResult.setResponseMessage('Fail');
WDS.log.error(e.message)
}
try{
wait.until(conditions.presenceOfElementLocated(pkg.By.xpath('/ruta_de elemento2_existente')));
WDS.log.info('OK2')
}catch(e){
WDS.sampleResult.setSuccessful(false);
WDS.sampleResult.setResponseMessage('Fail2');
WDS.log.error(e.message)
}
WDS.sampleResult.sampleEnd();
I hope someone can help me with this problem, because I need to use the headless option. Thank you very much for your time.
You can print the page source to jmeter.log file by using the following function:
WDS.log.info(WDS.browser.getPageSource())
Or even save it into a separate file like:
org.apache.commons.io.FileUtils.writeStringToFile(new java.io.File('test.html'), WDS.browser.getPageSource())
Or take screenshot on failure like:
WDS.browser.getScreenshotAs(org.openqa.selenium.OutputType.FILE).renameTo(new java.io.File('test.png'))
Check out The WebDriver Sampler: Your Top 10 Questions Answered article for more information.
Also be aware that if the machine where you run your Selenium tests doesn't have GUI you can still normally launch browsers using i.e. Xvfb on Linux or under Local System account on Windows

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

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)

Unable to Download csv file using werbdriver + java

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.

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