Java 如何使用 Selenium Webdriver 中的“上传图像按钮”上传文件/照片

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19025308/
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-12 13:29:10  来源:igfitidea点击:

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

javaseleniumselenium-webdriver

提问by Niyati

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

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

此代码仅打开系统窗口,但未选择任何照片/文件

回答by kyop

Try changing your code to:

尝试将您的代码更改为:

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

回答by Sebastian Carroll

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?

Kyop 的答案是正确的,但要使其工作,您发现的元素需要采用<input type="file" id="file_upload_button">. 您能否发布相关代码的 HTML 片段来验证这一点?

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?

另外,为什么要使用 XPath 使 id 查找复杂化?仅使用driver.findElement(By.id("file_upload_button"))代替有什么好处吗?

Source: this post

来源:这篇文章

回答by Raavan

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 sendKeyswith the absolute path of the image/file you want to upload.

说明:每个浏览按钮<input>在 DOM 中都有一个处于隐藏状态的标签。通过使用以下代码行,我们只需更改包含该<input>标签的标签的类和样式属性,使其可见并sendKeys()可以对其执行命令。之后,当您sendKeys使用要上传的图像/文件的绝对路径进行操作时。

回答by user3458411

I am using the idea that @Raavan explained.

我正在使用@Raavan 解释的想法。

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

例如:在此页面https://touch.facebook.com/marketplace/ sell/item/我成功使用以下代码:

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