Not able to upload the file in selenium webdriver - java

WebElement element=driver.findElement(By.name("file"));
element.click();
element.sendKeys("C:\Users\Minesh\Desktop\arch_logo.png);
The Above test case is just to select the file.
we have another button to upload the file.
If we run the program,only the window is getting pop up.
File is not getting selected.
And the input type is of button.
Please guide for the query

You need to escape each backslash so it can be considered as a file path:
driver.findElement(By.name("file"))
.sendKeys("C:\\Users\\Minesh\\Desktop\\arch_logo.png);

#user6203568 - You can update your code as below:
It should work as it is working for me. And give your test method priority as per your requirement. Just for Example I gave priority here as #Test(priority = 1). I hope it should work for you.
#Test(priority = 1)
public void CERTIFICATIONSSCREENUploadCertficationFilesValidation()
throws InterruptedException, AWTException {
//Click on File Upload Button
driver.findElement(By.xpath("//*[#id='certificationFile']")).click();
Thread.sleep(1000);
// Set the file name in the clipboard. Also following line of code will search file in your computer so make sure you provide correct file path.
StringSelection s = new StringSelection("C:\\Doc\\CertificationFile.xls");
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(s, null);
Thread.sleep(1000);
Robot robot1 = new Robot();
robot1.keyPress(KeyEvent.VK_ENTER);
robot1.keyRelease(KeyEvent.VK_ENTER);
robot1.keyPress(KeyEvent.VK_CONTROL);
robot1.keyPress(KeyEvent.VK_V);
robot1.keyRelease(KeyEvent.VK_V);
robot1.keyRelease(KeyEvent.VK_CONTROL);
robot1.keyPress(KeyEvent.VK_ENTER);
robot1.keyRelease(KeyEvent.VK_ENTER);
Thread.sleep(1000);
}

Related

When I run java jar file normally everything is okey, when run the same jar in task sheduler, there are some issues

I written program in java which, open browser, do screenshtot and save this screenshot. To take a screenshot of the bigger part of the screen, I reduce the screen zoom to 75%. If i run my file normally (just click in runnable jar) everything is okey. But when i run my jar file in task sheduler, program dont respect zoom and do screenshot in normally size (100%). I checked many times, and did everything correctly.
This is part of my code, which find element on side, passes in that place, zoom to 75%, wait 3 seconds and do screenshot.
WebElement element = driver.findElement(By.xpath("/html/body/grafana-app/div[2]/div/div[1]/div/div/div[1]/dashboard-grid/div/div[2]/div/plugin-component/panel-plugin-singlestat/grafana-panel/div/div[2]/ng-transclude/div"));
((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);", element); //find element by xpath and move there
JavascriptExecutor executor = (JavascriptExecutor)driver;
executor.executeScript("document.body.style.zoom = '0.75'"); // change zoom in browser to 75%
Thread.sleep(3000);
doScreenShot(); // function which do screenshot
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
private static void doScreenShot()
{
// doing a screenshot
File src= ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
try {
// now copy the screenshot to desired location using copyFile //method
FileUtils.copyFile(src, new File("C:/Users/pl-admin-gm3/Desktop/DailyReports/Urls Health/Screenshots/"+ serverNames[i] +" - " + j +".png"));
j++;
}
catch (IOException e)
{
System.out.println(e.getMessage());
}
}
try using sendkeys,
driver.findElement(By.tagName("html")).sendKeys(Keys.chord(Keys.CONTROL,Keys.SUBTRACT)); // Set to 90%
driver.findElement(By.tagName("html")).sendKeys(Keys.chord(Keys.CONTROL,Keys.SUBTRACT)); // Set to 80%
or resize the window if the application automatically adjust,
driver.get().manage().window().setSize(new Dimension(width, height));

Selenium message-error and message-success in java

I'm facing a problem with finding an element that does not exist. When I try to login into the application, if it failed login it will show the element -
dr.findElement(By.className("message-error ")).getText();
And after a successful login it will show this:
dr.findElement(By.className("message-success")).getText();
When I run the code and it doesn't find the element, then execution stops with the exception: element is not found
String mes=null;
mes=dr.findElement(By.className("message-success")).getText();
if(mes!=null) {
File out= new File("success.txt");
FileWriter fr =new FileWriter(out,true);
PrintWriter pw=new PrintWriter(fr);
pw.println(mes+"|"+user.get(i)+"|"+pass.get(i));
pw.close();
}
mes=dr.findElement(By.className("message-error")).getText();
if(mes!=null) {
File out= new File("error.txt");
FileWriter fr =new FileWriter(out,true);
PrintWriter pw=new PrintWriter(fr);
pw.println(mes+"|"+user.get(i)+"|"+pass.get(i));
pw.close();
}
The element does not appear.
For example, the success element will not shown until it is successful and the error element will not appear in the CSS until it gets an error.
So how can I tell it if element should exit or come to live or appear do an action?
What is the right thing to do in an if statement if the login is successful? Do this and login fail do this?
Use WebdriverWait to wait for the visibility of success message,
// After valid login
WebDriverWait wait = new WebDriverWait(driver, 60);
WebElement successmessage wait.until(ExpectedConditions.visibilityOfElementLocated(By.className("message-success")));
sucessmessage.getText();
Similarly for error message,
// After invalid login
WebElement errormessage wait.until(ExpectedConditions.visibilityOfElementLocated(By.className("message-error")));
errormessage.getText();
What i think is you have same element but the class getting change as per application behavior. suppose if you are able to login in the application then it show the message element with class having attribute message-success and if it won't allow then error message with class having attribute 'message-error' in the same element.
I've handled the same in below code -
// first get the message element with some other locator or other attribute (don't use class name)
WebElement message = driver.findElement(By.locator);
if(message.getAttribute("class").contains("message-success")){
System.out.println("Success message is " + message.getText())
// write the code to perform further action you want on login success
}else if (message.getAttribute("class").contains("message-error")){
System.out.println("Error message is " + message.getText())
// write the code to perform further action you want on login Fail
}else{
System.out.println("Message is empty" + message.getText())
}
Let me know if you have further queries.
My Choice is to use Webdriver wait. it is the perfect way to find an element.
public WebDriverWait(WebDriver driver,15)
WebElement successmessage = wait.until(ExpectedConditions.visibilityOfallElementLocatedby(By.className("message-success")));
sucessmessage.getText();
visibilityOfallElementLocatedby :
An expectation for checking that all elements present on the web page that match the locator are visible. Visibility means that the elements are not only displayed but also have a height and width that is greater than 0.
The above i wrote is for success Message, similar way try for invalid login.
To use different types of wait, check this doc - https://seleniumhq.github.io/selenium/docs/api/java/allclasses-noframe.html
search Wait in that document.
this is the answer for the question it work with me
try {
WebElement sucmes=dr.findElement(By.xpath("//div[#class='message']"));
String suclogin="login success:";
if(sucmes.getText().contains(suclogin)) {
File suclogin= new File("suclog.txt");
FileWriter suclogr =new FileWriter(suclogin,true);
PrintWriter suclogrw=new PrintWriter(suclogr);
suclogrw.println(sucmes.getText());
suclogrw.close();
}else{
//the other action here
}
}

Upload Local Image With Selenium WebDriver (Java)

I have looked at many answers and only found bits and pieces that worked to end up here, so basically I am using selenium to select the file input on the page, then execute some javascript to make it visible, and then send the file path to the keys.
all of this works but when I submit the form the image is not displayed on the final product, e.g. when I click submit and view my post there is no image
Here's my code:
WebElement imageUpload = driver.findElement(By.xpath(("//*[#id=\"FileInputWrapper\"]/input")));
Thread.sleep(600);
js.executeScript("arguments[0].setAttribute('type', 'file');", imageUpload);
Thread.sleep(600);
imageUpload.sendKeys(computerHome + "/downloads/testImageFolder/testImage.jpg");
Thread.sleep(600);
After Selenium does this, this appears above the submit image button:
This means it received my image but for some reason it also did not?
because when I click submit on the post the image is not visible there are no images.
Any ideas are very appreciated.
Thanks.
Below method will help you too browse the file and select it. Just pass 3 required parameters
Element type
Element locator
File path/resource
Here is the code:
/*------- FileUploading(): This method browse and the upload the selected file -------*/
public static void FileUpload(PropertyType ElementType, string Element, string FilePath)
{
if (ElementType == PropertyType.Id)
{
PropertyCollection.wdriver.FindElement(By.Id(Element)).Click();
}
else if (ElementType == PropertyType.XPath)
{
PropertyCollection.wdriver.FindElement(By.XPath(Element)).Click();
}
Thread.Sleep(3000);
SendKeys.SendWait(FilePath);
Thread.Sleep(3000);
SendKeys.SendWait(#"{Enter}");
Thread.Sleep(3000);
}

Uploading a file in Selenium

I want to upload two image (.png) files .I used action keys and send keys to upload the file.It is working fine for one file but if again i want to upload second image file,the file is not getting uploaded.
Actions action1 = new Actions(m.driver);
action1.moveToElement(m.driver.findElement(By.id("onetidIOFile"))).click();
WebElement s=m.driver.findElement(By.xpath("//input[#type='file']"));
s.sendKeys("path of one file");m.click("xpath", ".//[#id='attachOKbutton']");
m.click("id", "Ribbon.ListForm.Edit.Actions.AttachFile-Large");
action1.moveToElement(m.drive‌​r.findElement(By.id("onetidIOFile"))).click();
m.driver.findElement(By.xpath("//‌​input[#type='file']")).sendKeys("path of second file ");
m.key("Enter","attachOKbutton");
Can anyone help me in doing this???
#sajju - You can update your code as below:
It should work as it is working for me. And give your test method priority as per your requirement. Just for Example I gave priority here as #Test(priority = 1). I hope it should work for you.
#Test(priority = 1)
public void CERTIFICATIONSSCREENUploadCertficationFilesValidation()
throws InterruptedException, AWTException {
//Click on File Upload Button
driver.findElement(By.xpath("//*[#id='certificationFile']")).click();
Thread.sleep(1000);
// Set the file name in the clipboard. Also following line of code will search file in your computer so make sure you provide correct file path.
StringSelection s = new StringSelection("C:\\Doc\\CertificationFile.xls");
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(s, null);
Thread.sleep(1000);
Robot robot1 = new Robot();
robot1.keyPress(KeyEvent.VK_ENTER);
robot1.keyRelease(KeyEvent.VK_ENTER);
robot1.keyPress(KeyEvent.VK_CONTROL);
robot1.keyPress(KeyEvent.VK_V);
robot1.keyRelease(KeyEvent.VK_V);
robot1.keyRelease(KeyEvent.VK_CONTROL);
robot1.keyPress(KeyEvent.VK_ENTER);
robot1.keyRelease(KeyEvent.VK_ENTER);
Thread.sleep(1000);
}

Unable to execute Sikuli script after i click on the Web-element. ( Selenium webdriver with Java)

Here is my code
public static void main(String[] args) throws InterruptedException {
WebDriver driver = new FirefoxDriver();
//Open the URL
driver.get("http://www.toolsqa.com/automation-practice-form/");
//Maximize the window
driver.manage().window().maximize();
//Click on Button which will open file upload window
driver.findElement(By.xpath(".//*[#id='photo']")).click();
// Implementing Sikuli
ScreenRegion s = new DesktopScreenRegion();
Target target = new ImageTarget(new File("D://SELENIUM WORK-PLACE/File_upload//img//Capture.PNG"));
ScreenRegion r = s.wait(target, 20000);
r=s.find(target); // Locate the target on the screen.
//Create a Canvas object of the type DesktopCanvas.
Canvas test = new DesktopCanvas();
test.addBox(r);
test.addLabel(r, "I am present here");
test.display(5);
}
}
Actual Result : Clicks on the Web-element, It opens a File upload box. Nothing happens. ( But if i close the Box and re-open it manually then it works fine)
Expected Output- It should work at the first time we open the File upload box.
Your code is fine. Fix the path to: "D://SELENIUM WORK-PLACE//File_upload//img//Capture.PNG"
Then, try using the below image for getting the Filename textfield instead. Because bigger the size of image, there are more possibilities of Sikuli being unable to detect the element as even a pixel's change might get in the way of Sikuli identifying an element.:

Categories

Resources