在java中使用selenium web驱动程序。我有一个图像上传控件,我需要上传图像。我通过传递没有工作的图像路径尝试了.sendKeys方法。 我已经尝试过机器人类,首先点击打开一个Window(Windows原生窗口)的按钮,但它没有在"文件名"中键入键。区域。
<fieldset class="fieldset-company_logo post-fieldSet">
<label for="company_logo">Opportunity image:</label>
<div class="field">
<div class="upload-button">
<button class="button">Choose File</button>
<span>No file chosen</span>
<input class="input-text" name="company_logo" id="company_logo" placeholder="" type="file">
</div>
<small class="description"> Max. file size: 2MB. Allowed file format: jpg, gif, png </small>
</div>
</fieldset>
答案 0 :(得分:1)
我得到了我的问题的解决方案,请查看以下详细信息:
将数据设置为剪贴板的功能,我将使用此功能将图像路径设置为剪贴板,稍后我将在模型窗口中使用该文件:
public static void setClipboardData(String string) {
StringSelection stringSelection = new StringSelection(string);
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(stringSelection, null);
}
现在查看这些代码行
WebElement upload_btn = driver.findElement(By.xpath(choose_file_btn_xpath));
Thread.sleep(4000);
setClipboardData(selected_image_path);
Actions builder = new Actions(driver);
Action myAction = builder.click(upload_btn).release().build();
myAction.perform();
Robot rbt = new Robot();
rbt.delay(4000);
rbt.keyPress(KeyEvent.VK_CONTROL);
rbt.keyPress(KeyEvent.VK_V);
rbt.keyRelease(KeyEvent.VK_V);
rbt.keyRelease(KeyEvent.VK_CONTROL);
rbt.keyPress(KeyEvent.VK_ENTER);
rbt.keyRelease(KeyEvent.VK_ENTER);
rbt.delay(4000);
driver.findElement(By.xpath(submit_button_xpath)).click();
感谢您的帮助和支持。
答案 1 :(得分:1)
很高兴听到您找到了上传图片的方法。只是为了与您分享另一种方式。例如,如果单行中你需要上传文件夹中的所有图像/文件(一个或多个),你可以使用这个脚本:
@Test
public void Upload() throws InterruptedException
{
File images = new File("*path where all images are saved*");
File[] eimages = images.listFiles();
String imageList = "";
for(int i = 0; i < eimages.length; i++){
imageList += (i != 0 ?"\n":"") + eimages[i].getAbsolutePath();
}
driver.findElement(By.id("fileupload")).sendKeys(fishList);
Thread.sleep(5000);
System.out.println("Images Uploaded");
}