尝试单击浏览按钮时,显示Web驱动程序无效参数异常。该文件只能通过发送密钥附加,请帮助
显示运行时异常 这是我的 XPath
@FindBy(how=How.XPATH,using="//input[@type='file']")
private WebElement eleAttachDoc;
您正在尝试单击并上传文件。 单击时应显示一个窗口弹出窗口,硒无法处理,因此 可以使用带有文件位置(绝对路径(参数的 SendKeys 来处理此元素,该参数将直接上传文件。
根据问题,您正在尝试上传文件。
在某些字段中,根据设计,您可以直接发送路径。
driver.findElement(By.id("uploadfile_cv")).sendKeys("C:\mycv.pdf");
如果上述解决方案不仅有效,则可以使用 Java 工具包上传文件。请参阅下面的代码。请尝试此操作并提供反馈。
import java.awt.AWTException;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.event.KeyEvent;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.testng.annotations.AfterSuite;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
public class FileUploadUsingJavaToolKitExample {
WebDriver driver;
@Test(priority=1)
public void navigateToWebSiteAndUploadFile() throws UnsupportedFlavorException, IOException, InterruptedException, AWTException {
// Create a file object
File f = new File("resources\DemoUpload.txt");
// Get the absolute path of file f
String absoluteFilePath = f.getAbsolutePath();
//Copy the file path to clipboard
StringSelection autoCopiedFilePath = new StringSelection(absoluteFilePath);
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(autoCopiedFilePath, null);
//Navigate to the URL
driver.get("https://codepen.io/rcass/pen/MmYwEp");
driver.switchTo().frame("result"); //switching the frame by name
//Click on a button which opens the popup driver.findElement(By.xpath("//input[@id='fileToUpload']")).click();
Thread.sleep(2000);
//This will paste the file path and name in the file explorer by pressing Ctrl +V combination.
Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_V);
// Pause should be used here to perform the action properly and release the Ctrl +V keys
Thread.sleep(2000);
robot.keyRelease(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_CONTROL);
Thread.sleep(8000);
//press enter key after giving the file path.
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);
Thread.sleep(5000);
}
}