Java Selenium webdriver使用相对路径上传下载文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22718219/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 17:27:58  来源:igfitidea点击:

Selenium webdriver upload download files using relative path

javaeclipsemavenseleniumjenkins

提问by Kazman

I would like to upload a file with selenium webdriver. I can do this in local machine using the absolute path of the file : String filename = "C:\Windows\Temp\"+"templatePMT.html";. I'm using Eclipse and a maven project with a pom.xml and. I commit this project on SVN. I use Jenkins software to run the test of the Web app on IE8. Jenkins is deployed on Red Hat 5.0. ---- The problem is this : ---- how can I upload a file using a relative path instead of the absolute path ? The file is in resource folder of my project.

我想用 selenium webdriver 上传一个文件。我可以使用文件的绝对路径在本地机器上执行此操作:String filename = "C:\Windows\Temp\"+"templatePMT.html";。我正在使用 Eclipse 和一个带有 pom.xml 和的 maven 项目。我在 SVN 上提交了这个项目。我使用Jenkins软件在IE8上运行Web应用程序的测试。Jenkins 部署在 Red Hat 5.0 上。---- 问题是这样的: ---- 如何使用相对路径而不是绝对路径上传文件?该文件位于我的项目的资源文件夹中。

采纳答案by Robbie Wareham

You should look at file detectors. http://saucelabs.com/resources/selenium-file-upload

您应该查看文件检测器。http://saucelabs.com/resources/selenium-file-upload

回答by Matthew Wilson

You could get the absolute path of the resource file:

您可以获取资源文件的绝对路径:

URL resource = Main.class.getResource("/templatePMT.html");
String absolutePath = Paths.get(resource.toURI()).toString();

回答by gihanchanuka

You can use following code to get absolute path of the file and upload the content

您可以使用以下代码获取文件的绝对路径并上传内容

String filePath = System.getProperty("user.dir") + "/src/res/test.pdf; driver.findElement(By.id("elementID")).sendKeys(filePath);

String filePath = System.getProperty("user.dir") + "/src/res/test.pdf; driver.findElement(By.id("elementID")).sendKeys(filePath);

Also you can use find the element using cssSelector as well. Then the code would be; driver.findElement(By.cssSelector("input[id='elementId']")).sendKeys(filePath); See more regex here : Finding an element by partial id

您也可以使用 cssSelector 来查找元素。那么代码将是; driver.findElement(By.cssSelector("input[id='elementId']")).sendKeys(filePath); 在此处查看更多正则表达式:通过部分 ID 查找元素

Ref: Relative path of a file to upload a file

Ref: 上传文件的文件的相对路径