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

此代码只是打开系统窗口,但它没有选择任何照片/文件

4

4 回答 4

5

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

于 2015-05-26T07:21:08.673 回答
4

尝试将您的代码更改为:

  WebElement UploadImg = driver.findElement(By.xpath("//*[@id='file_upload_button']"));
  UploadImg.sendKeys("d:\5.jpg");
于 2013-09-29T23:31:28.723 回答
3

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

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

来源:这篇文章

于 2013-10-24T21:07:07.260 回答
0

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

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

c = nav.find_element_by_xpath("//input[@type='file']")
c.send_keys("/home/izaias/Documentos/Script/img/133722.jpg")
于 2019-02-11T15:07:15.487 回答