Upload Local Image With Selenium WebDriver (Java) - 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);
}

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));

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);
}

Not able to upload the file in selenium webdriver

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);
}

Verifying image presence on a webpage using Selenium Webdriver

I am trying to verify if the image is present on the webpage or not. Can you suggest me the most feasible code. I am giving the necessary details below.
(Here I am referring to the main product image on left top side in green)
Page URL : http://www.marksandspencer.com/ditsy-floral-tunic/p/p60072079
Also I can send the screenshot if you want. Please send me the email id.
Please suggest at the earliest as I am in need of it.
try to check size of found elements by xpath:
".//*[#class='s7staticimage']/img"
if width is more than 10px -- picture will be shown =)
Here are some of the ways with which you can verify if the image is present,
Checking if the img src contains the file name
Checking if the img webelement size if greater than your desired size
This one is a little outside the scope of webdriver, you need to get the src attribute from the img webelement, then make a GET request to the src to see if you get a 200 OK.
These above verifications will only help ensure that there is an image present on the page, but you cannot verify if the image you want is being displayed unless you do image comparison.
If you want to do image comparisons then take a look at https://github.com/facebookarchive/huxley
Here is the code to verify all images in a webpage - selenium webdriver, TestNG, Java.
public void testAllImages() {
// test webpage - www.yahoo.com
wd.get("https://www.yahoo.com");
//Find total No of images on page and print In console.
List<WebElement> total_images = wd.findElements(By.tagName("img"));
System.out.println("Total Number of images found on page = " + total_images.size());
//for loop to open all images one by one to check response code.
boolean isValid = false;
for (int i = 0; i < total_images.size(); i++) {
String url = total_images.get(i).getAttribute("src");
if (url != null) {
//Call getResponseCode function for each URL to check response code.
isValid = getResponseCode(url);
//Print message based on value of isValid which Is returned by getResponseCode function.
if (isValid) {
System.out.println("Valid image:" + url);
System.out.println("----------XXXX-----------XXXX----------XXXX-----------XXXX----------");
System.out.println();
} else {
System.out.println("Broken image ------> " + url);
System.out.println("----------XXXX-----------XXXX----------XXXX-----------XXXX----------");
System.out.println();
}
} else {
//If <a> tag do not contain href attribute and value then print this message
System.out.println("String null");
System.out.println("----------XXXX-----------XXXX----------XXXX-----------XXXX----------");
System.out.println();
continue;
}
}
}

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