简体   繁体   English

使用Selenium WebDriver(Java)上传本地图像

[英]Upload Local Image With Selenium WebDriver (Java)

I have looked at many answers and only found bits and pieces that worked to end up here, so basically I am using selenium to select the file input on the page, then execute some javascript to make it visible, and then send the file path to the keys. 我查看了许多答案,但只发现到最后可用的点点滴滴,所以基本上我使用硒来选择页面上的文件输入,然后执行一些javascript以使其可见,然后将文件路径发送至按键。

all of this works but when I submit the form the image is not displayed on the final product, eg when I click submit and view my post there is no image 所有这些都有效,但是当我提交表单时,图像未显示在最终产品上,例如,当我单击“提交”并查看我的帖子时,没有图像

Here's my code: 这是我的代码:

WebElement imageUpload = driver.findElement(By.xpath(("//*[@id=\"FileInputWrapper\"]/input")));
    Thread.sleep(600);
    js.executeScript("arguments[0].setAttribute('type', 'file');", imageUpload);
    Thread.sleep(600);
    imageUpload.sendKeys(computerHome + "/downloads/testImageFolder/testImage.jpg");
    Thread.sleep(600);

After Selenium does this, this appears above the submit image button: Selenium执行此操作后,它会显示在“提交图像”按钮上方:

出现文件输入(以前没有选择文件)

This means it received my image but for some reason it also did not? 这意味着它收到了我的图像,但由于某种原因也没有收到? because when I click submit on the post the image is not visible there are no images. 因为当我单击帖子上的提交时,该图像不可见,所以没有图像。

Any ideas are very appreciated. 任何想法都非常感谢。

Thanks. 谢谢。

Below method will help you too browse the file and select it. 下面的方法将帮助您浏览文件并选择它。 Just pass 3 required parameters 只需传递3个必需的参数

  1. Element type 元素类型
  2. Element locator 元素定位器
  3. File path/resource 文件路径/资源

Here is the code: 这是代码:

/*-------    FileUploading(): This method browse and the upload the selected file    -------*/
    public static void FileUpload(PropertyType ElementType, string Element, string FilePath)
    {
        if (ElementType == PropertyType.Id)
        {
            PropertyCollection.wdriver.FindElement(By.Id(Element)).Click();
        }
        else if (ElementType == PropertyType.XPath)
        {
            PropertyCollection.wdriver.FindElement(By.XPath(Element)).Click();
        }

        Thread.Sleep(3000);
        SendKeys.SendWait(FilePath);
        Thread.Sleep(3000);
        SendKeys.SendWait(@"{Enter}");
        Thread.Sleep(3000);
     }

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

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