简体   繁体   English

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

[英]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 . 说明:每个“浏览”按钮在DOM中都具有处于隐藏状态的<input>标记。 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. 通过使用下面的代码行,我们只需更改封闭<input>标签的标签的class和style属性,使其可见并可以对其执行sendKeys()命令。 After that when you do a sendKeys with the absolute path of the image/file you want to upload. 之后,当您使用要上传的图像/文件的绝对路径执行sendKeys时。

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"> . Kyop的答案是正确的,尽管要使其正常工作,您要找到的元素需要采用<input type="file" id="file_upload_button"> Could you post an HTML snippet of the relevant code to verify this? 您能否发布相关代码的HTML代码段以进行验证?

Also why complicate things with XPath for an id find? 另外,为什么要使用XPath将ID复杂化呢? Is there some benefit over just using driver.findElement(By.id("file_upload_button")) instead? 仅仅使用driver.findElement(By.id("file_upload_button"))会有一些好处吗?

Source: this post 资料来源: 这篇文章

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/selling/item/我正在成功使用以下代码:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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