Using selenium web driver with java. I have an image upload control using which i need to upload an image. I have tried .sendKeys method by passing image path that didn't work.
I have tried robot class, first clicks the button that opens a Window (windows native window) but it didn't type the keys in the "File Name" area.
<fieldset class="fieldset-company_logo post-fieldSet">
<label for="company_logo">Opportunity image:</label>
<div class="field">
<div class="upload-button">
<button class="button">Choose File</button>
<span>No file chosen</span>
<input class="input-text" name="company_logo" id="company_logo" placeholder="" type="file">
</div>
<small class="description"> Max. file size: 2MB. Allowed file format: jpg, gif, png </small>
</div>
</fieldset>
I got the solution for my question please review below details:
Function to set data to clip board, I will user this to set image path to clip board that I will user later on model window:
public static void setClipboardData(String string) {
StringSelection stringSelection = new StringSelection(string);
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(stringSelection, null);
}
Now review these lines of code
WebElement upload_btn = driver.findElement(By.xpath(choose_file_btn_xpath));
Thread.sleep(4000);
setClipboardData(selected_image_path);
Actions builder = new Actions(driver);
Action myAction = builder.click(upload_btn).release().build();
myAction.perform();
Robot rbt = new Robot();
rbt.delay(4000);
rbt.keyPress(KeyEvent.VK_CONTROL);
rbt.keyPress(KeyEvent.VK_V);
rbt.keyRelease(KeyEvent.VK_V);
rbt.keyRelease(KeyEvent.VK_CONTROL);
rbt.keyPress(KeyEvent.VK_ENTER);
rbt.keyRelease(KeyEvent.VK_ENTER);
rbt.delay(4000);
driver.findElement(By.xpath(submit_button_xpath)).click();
Thanks for your help and support.
Glad to hear that you found a way for uploading image. Just to share with you another way of doing this. At instance, if in single go you need to upload all images/files (one or more) sitting in a folder, you can use this script:
#Test
public void Upload() throws InterruptedException
{
File images = new File("*path where all images are saved*");
File[] eimages = images.listFiles();
String imageList = "";
for(int i = 0; i < eimages.length; i++){
imageList += (i != 0 ?"\n":"") + eimages[i].getAbsolutePath();
}
driver.findElement(By.id("fileupload")).sendKeys(fishList);
Thread.sleep(5000);
System.out.println("Images Uploaded");
}
Related
Org.openqa.selenium.ElementNotInteractableException: element not interactable
When I try to upload file but when I use action 'click', window to upload file is visible
#FindBy(id = "uniform-fileUpload")
WebElement uploadFile;
So when I try this method:
public void uploadFile(){
uploadFile.click();
}
Everything is ok and window to select file is open so element is visible.
But when I try this:
uploadFile.sendKeys("C:\\test.png");
}
I have exeption:
org.openqa.selenium.ElementNotInteractableException: element not interactable
Page:
http://automationpractice.com/index.php?controller=contact
You are trying to send keystrokes to a div. You need to select on the input under the div, and then send the keystrokes to that instead.
<div class="uploader" id="uniform-fileUpload">
<input type="file" name="fileUpload" id="fileUpload" class="form-control">
...
</div>
Try id fileUpload instead.
Change this
#FindBy(id = "uniform-fileUpload")
WebElement uploadFile;
to
#FindBy(id = "fileUpload")
WebElement uploadFile;
Since this is the input element that needs to be the target for your file input.
I had this error when doing something like this in a generic methiod:
element.Clear(); // <-- OpenQA.Selenium.ElementNotInteractableException
element.SendKeys(value);
Turns out, that you cannot use the Clear() function on an <input type="file"/> dialog.
I am trying to upload file using sendkeys()
but selenium webdriver test fails with error:
"The element is not yet visible: By.xpath: //input[#id='upload-file-pc']"
Here is the html:
<input id="upload-file-pc" class="file-field-input" type="file" onchange="return validateFileSelected(this);" name="upload-file-pc"/>
<a class="dropbox-dropin-btn dropbox-dropin-default file-field-link" href="Javascript:void(0);">
<span class="dropin-btn-status"/>
Choose from Computer
</a>
Code:
String fileLocation = CommonConstants.TEST_FILE_LOCATION + this.config.getString("simpletext");
logger.info("text file location: {}", fileLocation);
WebExecutionHelper.waitForElementVisible(driver, By.xpath("//input[#type='file']")).sendKeys(fileLocation);
Upload Button Image:
Please help
Selenium probably doesn't operate on hidden elements. What you can do is force it to appear with executeScript:
// get <input> element
input = driver.findElementById("upload-file-pc")
// make it visible
driver.executeScript(`
var input = arguments[0];
input.className = '';
input.style.display = 'block';
input.style.position = 'fixed';
input.style.bottom = 0;
input.style.left = 0;
`, input)
// set the file
input.sendKeys(fileLocation)
Selenium can't operate (e.g sendKeys, click) on invisible element.
You can send the uploaded file's absolute path in backgroud by executeScript.
Java example:
WebElement fileUpload = driver.findElement(By.css("#upload-file-pc"));
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("return arguments[0].value=arguments[1];", fileUpload);
I am trying to upload a file using selenium send keys, but not working, .In my case button name is Attach Sign Off , its not working for it. Please help
<form class="v-upload v-widget v-upload-immediate" enctype="multipart/form-data" method="post" action="https://gbl04115.systems.uk.hsbc:8571/DSLWeb/APP/UPLOAD/2/921/action/3305f203-9e0c-4213-aecd-6ee2b2b29eb1" target="921_TGT_FRAME">
<div aria-describedby="gwt-uid-2">
<input type="hidden"/>
<input class="gwt-FileUpload" type="file" name="921_file" aria-describedby="gwt-uid-2"/>
<div class="v-button" tabindex="0" role="button" aria-hidden="false" aria-describedby="gwt-uid-2">
<span class="v-button-wrap">
<span class="v-button-caption">Attach Sign-off</span>
</span>
Try this one and let me know if it not works
WebElement fileInput = driver.findElement(By.className("gwt-FileUpload"));
fileInput.sendKeys("C:/path/to/file.jpg");
I hope this answer will help to solve your issue. But i have not tested yet.
WebElement fileInput = driver.findElement(By.name("uploadfile"));
fileInput.sendKeys("C:/path/to/file.jpg");
(OR)
driver.findElement(By.id("inputFile")).sendKeys("C:/path/to/file.jpg");
#AutoMater - 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);
}
List elements = driver.findElements(By.className("gwt-FileUpload"));
elements.get(1).sendKeys(filePath);
It worked using above code.
Thanks #Andersson
I am constantly getting "No Such Element Exception" for "First Name" test box
Below is my code:
public class southwestSignUpSave {
WebDriver oBrw;
#Before
public void loadwebsite (){
oBrw = new FirefoxDriver();
oBrw.manage().window().maximize();
oBrw.get("https://southwest.com");
oBrw.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
#Test
public void signUpAndSave(){
oBrw.findElement(By.partialLinkText("OFFERS")).click();
oBrw.findElement(By.partialLinkText("Sign")).click();
//oBrw.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
WebDriverWait oWait = new WebDriverWait(oBrw, 30);
oWait.until(ExpectedConditions.presenceOfElementLocated(By.id("FIRST_NAME")));
oBrw.findElement(By.id("FIRST_NAME")).clear();
oBrw.findElement(By.id("FIRST_NAME")).sendKeys("abc");
oBrw.findElement(By.id("LAST_NAME")).clear();
oBrw.findElement(By.id("LAST_NAME")).sendKeys("asd");
oBrw.findElement(By.id("EMAIL")).clear();
oBrw.findElement(By.id("EMAIL")).sendKeys("abc#asd.com");
new Select(oBrw.findElement(By.id("HOME_AIRPORT"))).selectByVisibleText("Akron/Canton, OH - CAK");
oBrw.findElement(By.id("IAN")).click();
}
}
I tried to use id and name.
where am I going wrong. I am new to Selenium WD
U can try finding the element using xpath. For that u need to install the firepath plugin in firefox and then inspect the element using firepath.
oBrw.findElement(By.xpath("copy paste the xpath here")).clear();
I would also recommend loading the driver using System property inside loadwebsite() method.
System.setProperty("webdriver.firefox.driver", "//your driver path");
oBrw=new FirefoxDriver();
if the Sign page opens in a new tab/window then u need to navigate to that tab/window because Selenium by default stays in the opening tab. To navigate u need to add the following lines of code after clicking on "Sign"-
Set<String> s=wd.getWindowHandles();
Iterator<String> it=s.iterator();
it.next();//control goes to 1st default tab
String str=it.next().toString();//control goes to the next tab
oBrw.switchTo().window(str);//driver switches to the new window/tab.
if the element is present inside a frame then also u need to switch to that frame first before finding element inside it. Below is the code-
WebElement web=oBrw.findElement(By.xpath("copy paste your frame xpath"));
oBrw.switchTo.frame(web);
now try to find the element present in the new tab/window.
FIRST NAME input text field is inside iframe. Check the below piece of HTML.
<iframe frameborder="0" src="https://luv.southwest.com/servlet/formlink/f?kOHpjQACAY" onload="scroll(0,0);" verticalscrolling="no" horizontalscrolling="no" scrolling="no" title="Click 'n Save signup form"></iframe>
<html dir="ltr">
<head>
<body>
<p>
<span class="required">*Required</span>
</p>
<div class="clear"></div>
<form id="cnsForm" onsubmit="return validateForm();" action="https://luv.southwest.com/servlet/campaignrespondent" method="POST">
<div class="form_field first_name">
<label for="first_name">
<input id="FIRST_NAME" type="text"=""="" maxlength="25" size="22" name="FIRST_NAME">
</div>
...
Hence selenium is unable to find out the element. Here we need to explicitly switch to iframe as below. Insert below code snippet before you find FIRST_NAME. (You can insert well formatted xpath of iframe. I just grabbed it from firebug.)
WebElement iframeSwitch = oBrw.findElement(By.xpath("/html/body/div[1]/div[3]/div[2]/div[1]/div/div/div[4]/div/div/div/div[3]/iframe"));
oBrw.switchTo().frame(iframeSwitch);
That Text box is inside an iFrame, so you need to switch to that iFrame first then try findElement method to locate textbox.
oBrw.findElement(By.partialLinkText("OFFERS")).click();
oBrw.findElement(By.partialLinkText("Sign")).click();
oBrw.switchTo().defaultContent();
oBrw.switchTo().frame(0);
WebElement id = oBrw.findElement(By.name("FIRST_NAME"));
id.sendKeys("USERNAME");
Hope this helps.
i'm trying to upload some sonar ruleset files to multiple sonars.
i want to get help by web ui automator using Selenium.
i wrote some java code but it still doesn't work.
*added comment
bellowed code works on chrome driver but it doesn't work on safari driver.
please tell me how to modify code to work for multiple browser.
here is my code
public void openQualityProfiles() {
String linkTextSettings = "Settings";
String cssSelector = ".dropdown-menu > ul > li > a";
WebElement settings = waitForElement(By.linkText(linkTextSettings));
settings.click();
WebElement qualityProfiles = waitForElement(By.cssSelector(cssSelector));
qualityProfiles.click();
}
public WebElement waitForElement(By locator) {
WebElement target = null;
WebDriverWait wait = new WebDriverWait(driver, 10);
target = wait.until(ExpectedConditions.elementToBeClickable(locator));
return target;
}
and here is HTML
Settings
<div id="admin-panel" class="dropdown-menu" style="display: none">
<ul>
<li>Quality Profiles</li>
<li>Configuration</li>
<li>Security</li>
<li>System</li>
If your submenu appears when mouse is over, you can use:
new Actions(driver).moveToElement(yourMenu).build().perform();
or try to click on
driver.findElement(By.className("link-more")).click();