There are many questions which are similar to this has been asked in Stackoverflow. But this is something different
I am now currently automating an web application in which at the end of the application, PDF will be generated (Which will be displayed as a link, on clicking it PDF will open in a new window).
I am now currently using AUTOIT to automate Save AS dialog box. Is there any other way to download without using AutoIT.
I tried fetching the PDF URL from the link in the application under tag, but it is actually invoking a JS to open a PDF in new Window
In new window PDF is actually in Embed tag in which src is about::blank
I fetched PDF complete src but when I used that URL without clearing any cookies, I am unable to get the PDF
Is there any suggestions for this issue?
Upload File Using ROBOT Class
public String imagePath = System.getProperty("user.dir") +"\\src\\test\\java\\filepath.pdf";
public void uploadFileWithRobot(String imagePath) {
StringSelection stringSelection = new StringSelection(imagePath);
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
clipboard.setContents(stringSelection, null);
Robot robot = null;
try {
robot = new Robot();
} catch (AWTException e) {
e.printStackTrace();
}
robot.delay(250);
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_ENTER);
robot.delay(150);
robot.keyRelease(KeyEvent.VK_ENTER);
}
Now Click on PDF and its open in new window than Verify text is present or not in PDF
public String readPDFInURL(String text) throws EmptyFileException, IOException {
System.out.println("Enters into READ PDF");
String output = "";
URL url = new URL(driver.getCurrentUrl());
System.out.println("url : " + url);
InputStream is = url.openStream();
BufferedInputStream fileToParse = new BufferedInputStream(is);
PDDocument document = null;
try {
document = PDDocument.load(fileToParse);
output = new PDFTextStripper().getText(document);
if (output.contains(text)) {
System.out.println("Element is matched in PDF is : " + text);
test.log(LogStatus.INFO, "Element is displayed in PDF " + text);
} else {
System.out.println("Element is not matched in PDF");
test.log(LogStatus.ERROR, "Element is not displayed in PDF :: " + text);
throw new AssertionError("Element is not displayed" + text);
}
} finally {
if (document != null) {
document.close();
}
fileToParse.close();
is.close();
}
return output;
}
Yes. You can download a file without using third party like AutoIT. Below is the code that works perfectly fine,
First you have to switch to the window.
Then apply some wait. So that the page will be loaded completely.
Now you have to trigger key events i.e. ctrl + s
Pop-up will be appeared on the page to save your file.
Just hit enter. So that you can save your file.
String str = TestUtil.switchToWindow();
pause(3000);
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
Thread.sleep(2000);
Robot robot = new Robot();
Thread.sleep(1000);
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_S);
robot.keyRelease(KeyEvent.VK_S);
robot.keyRelease(KeyEvent.VK_CONTROL);
Thread.sleep(2000);
robot.keyPress(KeyEvent.VK_ENTER);
Thread.sleep(2000);
robot.keyPress(KeyEvent.VK_TAB); // file replace move to yes button
Thread.sleep(2000);
robot.keyPress(KeyEvent.VK_ENTER);
TestUtil.switchBackToParentWindow(str);
Related
Robot robot = new Robot();
Rectangle rectangle = new Rectangle(75, 124, 1095, 480);
File file = new File("screen-capture.jpg");
Desktop.getDesktop().open(new File("C:\\Users\\AnubhavPatel\\Desktop\\Testing_Code.xlsx"));
Thread.sleep(7000);
BufferedImage bufferedImage = robot.createScreenCapture(rectangle);
boolean status = ImageIO.write(bufferedImage, "jpg", file);
System.out.println("Screen Captured ? " + status + " File Path:- " + file.getAbsolutePath());
Runtime.getRuntime().exec("cmd /c taskkill /f /im excel.exe");
Open the file with a library, and then close it with the library's close command.
Right now, you are sending a kill command to Excel. Excel doesn't get a message you want to close a file, it gets the message it needs to shut down. You can't make this kind of an approach inform excel to close a file.
I used this approach-
//Open the excel file using Desktop.getDesktop()
Desktop.getDesktop().open(new
File("C:\\Users\\AnubhavPatel\\Desktop\\Testing_Code_Macro.xlsm"));
Thread.sleep(5000);
//Save and close it using robot class
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_S);
robot.keyRelease(KeyEvent.VK_S);
robot.keyRelease(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_ALT);
robot.keyPress(KeyEvent.VK_F4);
robot.keyRelease(KeyEvent.VK_F4);
robot.keyRelease(KeyEvent.VK_ALT);
Thread.sleep(5000);
//Then write to it using outputStream
FileOutputStream outputStream = new FileOutputStream(
"C://Users//AnubhavPatel//Desktop/Testing_Code_Macro.xlsm");
workbook.write(outputStream);
outputStream.close();
I am trying to upload a file in selenium webdriver using java in IE11. Below code is clicking on Browse button but it is not entering or pasting the file name to be uploaded on the newly opened window. It just stucks and nothing happens. Not able to debug the code also.Seems that Robot Class is not responding.
I also tried Send keys also but the behaviour is not consistent.
<input name="ctl00$PlaceHolderMain$UploadDocumentSection$ctl05$InputFile" title="Choose a file" class="ms-fileinput ms-fullWidth" id="ctl00_PlaceHolderMain_UploadDocumentSection_ctl05_InputFile" onfocus="ResetSpFormOnSubmitCalled();" onchange="CheckAssetLibMediaExtension()" type="file" size="35">
driver.manage().window().maximize(); WebElement element12 = (new WebDriverWait(driver, 10)).until(ExpectedConditions.elementToBeClickable(Main.newdocument(driver))); Main.newdocument(driver).click(); Thread.sleep(500); element12 = driver.findElement(By.xpath("//iframe[#class='ms-dlgFrame']")); driver.switchTo().frame(element12);
Thread.sleep(2000);
WebElement element = driver.findElement(By.xpath("//input[#type='file']"));
JavascriptExecutor executor = (JavascriptExecutor)driver;
executor.executeScript("arguments[0].click();", element);
Robot robot = new Robot();
StringSelection sel = new StringSelection("C:\\Users\\m9kuil\\Desktop\\ImportAttendeeTemplate.xlsx");
// Copy to clipboard
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(sel,null);
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_V);
// Release CTRL+V
robot.keyRelease(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_CONTROL);
//Press Enter
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);
robot.delay(1000);
Try once by writing robot.delay(10000); before comment //Press Enter
Other simple alternative for uploading file without robot class :
driver.findElement(By.xpath(".//input[#type='file']")).sendKeys("C:\\Users\\m9kuil\\Desktop\\ImportAttendeeTemplate.xlsx");
wait(10000)
I tried to upload the file using JUNIT_Selenium.
WebElement fileInfo = driver.findElement(By.xpath("//input[#type='file']"));
fileInfo.sendKeys('my file root');
But, the popup window was not closed in this way :(
Cloud you please give me the answer to solve this problem?
(browser used : Chrome)
I have used some special library Robot.
details.ClickChooseFile();
StringSelection ss = new StringSelection("C:\\Your File");
waitmethod.Waitsec();
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss, null);
Robot robot = new Robot();
waitmethod.Waitsec();
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);
details.ClickSubmitEmpl();
While uploading file in http://pdftableconverter.com/ with selenium
I have a problem to download file converted
to download xls file I need to click on the Like button which found in ajax web page check link to open image to see the problem
https://drive.google.com/file/d/0B4cxDnPAjctLOFcyZ29xeENHSG8/view?usp=sharing
My problem i need to click the like button to download the xls file
WebDriver driver = new FirefoxDriver();
driver.get("http://pdftableconverter.com/");
File file=null;
try {
file = new File(SeleniumProg.class.getClassLoader().getResource("21.pdf").toURI());
Assert.assertTrue(file.exists());
System.out.println("File Exited");
driver.findElement(By.name("userfile")).sendKeys(file.getAbsolutePath());
WebElement browseButton = driver.findElement(By.id("uploadButton"));
new Actions(driver).click(browseButton).perform();
//put path to your image in a clipboard
StringSelection ss = new StringSelection(file.getAbsolutePath());
//To Clear User Selection
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss, null);
//imitate mouse events like ENTER, CTRL+C, CTRL+V
Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);
WebElement d = driver.findElement(By.id("email"));
d.sendKeys("osama70087#gmail.com");
driver.findElement(By.id("submit_form")).click();
System.out.println("kkkkkkkk");
I use the following lines to simulate a Control_A [ select all ] key action in Java with robot, but the clipboard is not getting the text, why ?
Robot robot=null;
try { robot=new Robot(); }
catch (AWTException ex) { System.err.println("Can't start Robot: " + ex); }
robot.mouseMove(260,500);
robot.mousePress(InputEvent.BUTTON1_MASK);
// robot.mouseMove(660,700);
robot.mouseRelease(InputEvent.BUTTON1_MASK);
robot.keyPress(KeyEvent.VK_CONTROL); // Select all
robot.keyPress(KeyEvent.VK_A);
robot.keyRelease(KeyEvent.VK_A);
robot.keyRelease(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_CONTROL); // Copy
robot.keyPress(KeyEvent.VK_C);
robot.keyRelease(KeyEvent.VK_C);
robot.keyRelease(KeyEvent.VK_CONTROL);
Transferable t=Toolkit.getDefaultToolkit().getSystemClipboard().getContents(null);
try
{
if (t!=null && t.isDataFlavorSupported(DataFlavor.stringFlavor))
{
String text=(String)t.getTransferData(DataFlavor.stringFlavor);
System.out.println(text);
}
}
catch (Exception ex) { ex.printStackTrace(); }
I have a browser open so at [260,500] on screen there is text at that area. What have I missed ?
Edit:
I just found something strange, when I opened a browser, the text in the browser is not copies, but if I open a notepad/wordpad, the text in them will be copies, so why the browser didn't do it ?
All of your code should be inside the try block where you instantiate the Robot because you could end up trying to work with a null reference and get a NullPointerException. And if your Robot never got created and never copied contents, there'd be no point in you trying to access the contents from the clipboard either.
I'm not entirely sure why but adding a small delay before trying to read from the clipboard fixes things. I'm guessing it might have to do with a race condition between Java getting hold of the clipboard before the system has had time to update it.
This updated code should work:
Robot robot = null;
try
{
robot = new Robot();
robot.mouseMove(260, 500);
robot.mousePress(InputEvent.BUTTON1_MASK);
// robot.mouseMove(660,700);
robot.mouseRelease(InputEvent.BUTTON1_MASK);
robot.keyPress(KeyEvent.VK_CONTROL); // Select all
robot.keyPress(KeyEvent.VK_A);
robot.keyRelease(KeyEvent.VK_A);
robot.keyRelease(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_CONTROL); // Copy
robot.keyPress(KeyEvent.VK_C);
robot.keyRelease(KeyEvent.VK_C);
robot.keyRelease(KeyEvent.VK_CONTROL);
try
{
//sleep just a little to let the clipboard contents get updated
Thread.sleep(25);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
Transferable t = Toolkit.getDefaultToolkit().getSystemClipboard().getContents(null);
try
{
if (t != null && t.isDataFlavorSupported(DataFlavor.stringFlavor))
{
String text = (String) t.getTransferData(DataFlavor.stringFlavor);
System.out.println(text);
}
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
catch (AWTException ex)
{
System.err.println("Can't start Robot: " + ex);
}
Not sure of your code context but I had the same problem trying to extract the text from a PDF document on the browser.
It was misleading because the ctrl-a was highlighting the text but ctlr-c copied nothing. My solution was first to simulate a click anywhere on the document first, then ctrl-a and ctrl-c. My code:
robot = new Robot();
//Get window size
Dimension d = driver.manage().window().getSize();
System.out.println("Dimension x and y :"+d.getWidth()+" "+d.getHeight());
int x = (d.getWidth()/4)+20;
int y = (d.getHeight()/10)+50;
robot.mouseMove(x,y);
//Clicks Left mouse button
robot.mousePress(InputEvent.BUTTON1_DOWN_MASK);
robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
Thread.sleep(25);
// Select all
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_A);
robot.keyRelease(KeyEvent.VK_A);
robot.keyRelease(KeyEvent.VK_CONTROL);
Thread.sleep(100);
// Copy to clipboard
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_C);
robot.keyRelease(KeyEvent.VK_C);
robot.keyRelease(KeyEvent.VK_CONTROL);
Thread.sleep(100);
Hope this helps.