简体   繁体   中英

How to Upload File/Photo using “Upload Image Button” in Selenium Webdriver

  WebElement UploadImg = driver.findElement(By.xpath("//*[@id='file_upload_button']"));
  UploadImg.click();
  WebElement frame =driver.switchTo().activeElement();
  frame.sendKeys("d:\5.jpg");

This code just open system window but it doesn't select any Photo/File

Try changing your code to:

  WebElement UploadImg = driver.findElement(By.xpath("//*[@id='file_upload_button']"));
  UploadImg.sendKeys("d:\5.jpg");

Run This code :

JavascriptExecutor js = (JavascriptExecutor) driver; 
js.executeScript("arguments[0].setAttribute('style', arguments[1])",` driver.findElement(By.xpath("//input[@type='file']")), "0");
js.executeScript("arguments[0].setAttribute('class', arguments[1])", driver.findElement(By.xpath("//input[@type='file']/../../div[2]")), "a");
driver.findElement(By.xpath("//input[@type='file']")).sendKeys("Your Path to the file your system");

Explanation: Every Browse button has a <input> tag in DOM in hidden state . By using the below lines of code, we just change the class and style attributes of the tags enclosing that <input> tag so that it becomes visible and a sendKeys() command can be performed on it. After that when you do a sendKeys with the absolute path of the image/file you want to upload.

Kyop's answer is correct, though for this to work the element you are finding needs to be in the form <input type="file" id="file_upload_button"> . Could you post an HTML snippet of the relevant code to verify this?

Also why complicate things with XPath for an id find? Is there some benefit over just using driver.findElement(By.id("file_upload_button")) instead?

Source: this post

I am using the idea that @Raavan explained.

For instance: On this page https://touch.facebook.com/marketplace/selling/item/ I am using the following code with success:

c = nav.find_element_by_xpath("//input[@type='file']")
c.send_keys("/home/izaias/Documentos/Script/img/133722.jpg")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM