如何在selenium webdriver中上载具有相对路径的文件

如何在selenium webdriver中上载具有相对路径的文件,selenium,webdriver,Selenium,Webdriver,我正在使用selenium automation,无法上载具有相对路径的文件。请参阅下面的代码 driver.findElement(By.xpath("//span[text()='Theme']")).click(); File filepath=new File("\ntwinelogin.jpg"); WebElement fileobj = driver.findElement(By.name("toplogoupload")); fileobj.sendKeys("\ntwinel

我正在使用selenium automation,无法上载具有相对路径的文件。请参阅下面的代码

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

对当前项目目录路径使用
System.getProperty(“user.dir”)

System.getProperty("user.dir")+"\ntwinelogin.jpg";

步骤1:首先将文件存储在一个变量中,例如
String path=“C:\\users\\home\\newhtml.html”

步骤2:将变量传递给
sendkeys()
方法

driver.findelement(By.xapth("")).sendkeys(path);

对于Python中的相对路径,可以使用以下函数:

进口

import sys, os
使用以下代码:

ROOT_DIR = os.path.dirname(os.path.abspath(__file__))
screenshotpath = os.path.join(os.path.sep, ROOT_DIR,'YOURFOLDERNAME'+ os.sep)
print screenshotpath
确保创建了存在.py文件的文件夹

Java

System.getProperty("user.dir")

我最近需要一个平台无关的解决方案来解决这个问题。因为我们使用的是Maven,所以我实现了以下解决方案

Maven目录结构

试验


您应该获取绝对路径并将其与文件名连接起来,然后将其传递给.similer
src
 |
  - main
 |    |
 |     - java
 |         |
 |          - com
 |             |
 |              - example
 |                   |
 |                    - integration
 |                            |
 |                             - Test1.java
 |                            |
 |                             - Test2.java
 |                            ...
 |
  - resources
        |
         - File1.csv
        |
         - File2.csv
        ...
// 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);