how to upload file with relative path in selenium webdriver

Viewed 14929

I am working with selenium automation and I am not able to upload file with relative path please see the below code.

driver.findElement(By.xpath("//span[text()='Theme']")).click();

File filepath=new File("\ntwinelogin.jpg");
WebElement fileobj = driver.findElement(By.name("toplogoupload"));
fileobj.sendKeys("\ntwinelogin.jpg");
String Filepath=filepath.getAbsolutePath();
Filepath.trim();
4 Answers

You can use below function for relative path in Python:

Import

import sys, os

Use code as below :

ROOT_DIR = os.path.dirname(os.path.abspath(__file__))
screenshotpath = os.path.join(os.path.sep, ROOT_DIR,'YOURFOLDERNAME'+ os.sep)
print screenshotpath

make sure you create folder where .py file is present

Java

System.getProperty("user.dir")

I recently required a platform-agnostic solution to this problem. Since we were using Maven, I implemented the following solution.

Maven directory structure

src
 |
  - main
 |    |
 |     - java
 |         |
 |          - com
 |             |
 |              - example
 |                   |
 |                    - integration
 |                            |
 |                             - Test1.java
 |                            |
 |                             - Test2.java
 |                            ...
 |
  - resources
        |
         - File1.csv
        |
         - File2.csv
        ...

Test

// Load a file on the classpath as a resource using the ClassLoader.
URL    url  = getClass().getClassLoader().getResource("File1.csv");

// Convert the URL into a URI.
URI    uri  = file.toURI();

// Load the file from the URI.
File   file = new File(uri);

// Get the absolute path to the file.
String path = file.getAbsolutePath();

// Use the absolute path with Selenium.
input.sendKeys(path);
Related