Java、Selenium和Method.invoke():获取NoSuchMethodException
目标:创建我自己的方法,调用传入其中的Selenium方法,并重复该方法指定的次数 问题:无论我尝试什么,以下代码总是导致: java.lang.NoSuchMethodException:org.openqa.selenium.WebDriver.sendKeys() 讨论:据我所知,sendKeys()是org.openqa.selenium.WebDriver中/的一种方法 问题代码: 方法objTest=WebDriver.class.getMethod(strMethod,CharSequence.class) 其中strMethod=sendKeys 代码Java、Selenium和Method.invoke():获取NoSuchMethodException,java,selenium,selenium-webdriver,nosuchmethoderror,Java,Selenium,Selenium Webdriver,Nosuchmethoderror,目标:创建我自己的方法,调用传入其中的Selenium方法,并重复该方法指定的次数 问题:无论我尝试什么,以下代码总是导致: java.lang.NoSuchMethodException:org.openqa.selenium.WebDriver.sendKeys() 讨论:据我所知,sendKeys()是org.openqa.selenium.WebDriver中/的一种方法 问题代码: 方法objTest=WebDriver.class.getMethod(strMethod,CharSe
public void repeatAction(String strMethod, int numberOfTimes) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
int i = 0;
Method objTest = WebDriver.class.getMethod(strMethod, CharSequence.class); // PROBLEM CODE - results in NoSuchMethodException
while (i <= numberOfTimes) {
objTest.invoke(strMethod, Keys.DOWN); // I've hardcoded Keys.DOWN for now but will make this flexible later
i++;
}
}
运行时错误
Exception in thread "main" java.lang.NoSuchMethodException: org.openqa.selenium.WebDriver.sendKeys(java.lang.CharSequence)
at java.base/java.lang.Class.getMethod(Class.java:2109)
at AutocompleteDropdownPractice.repeatKeysAction(AutocompleteDropdownPractice.java:17)
at AutocompleteDropdownPractice.main(AutocompleteDropdownPractice.java:45)
对于我所做的错误以及我应该如何做的任何帮助,我们将不胜感激。如果您查看,您将看到没有任何WebDriver
类作为sendKeys()的方法,这正是您获得NoSuchMethodException的原因
我想您正在寻找org.openqa.selenium.WebElement.sendKeys(java.lang.CharSequence…keystend)
方法,在您的例子中,您可以按如下方式使用它:
Method objTest = WebElement.class.getMethod(strMethod, CharSequence[].class);
我使用数组版本CharSequence[].class
而不是CharSequence.class
,因为sendKeys
方法接受一个CharSequence.class
数组,该数组可以在中清楚地看到。首先
如果参考Java文档,您将看到它包含两个参数:
methodobjtest=WebDriver.class.getMethod(strMethod,CharSequence.class);
调用对象测试(strMethod,Keys.DOWN);
这意味着您从WebDriver
类中获取方法,并在String
对象上调用它,这是不正确的
秒
sendKeys
方法在WebElement
界面中声明,而不是在WebDriver
中声明
第三
您可以使用Proxy
对象来完成您正在尝试的操作,如下所示:
publicwebelement-poxiedElement(stringmethodname,int-times,WebElement){
return(WebElement)Proxy.newProxyInstance(this.getClass().getClassLoader(),new Class[]{WebElement.Class},new InvocationHandler()){
@凌驾
公共对象调用(对象o、方法、对象[]对象)抛出可丢弃的{
对象[]结果=新对象[次数];
if(methodName.equals(method.getName())){
for(int i=0;i
p.S.-您应该了解方法可以返回值。因此多次调用任何方法可能会返回多个值。你必须考虑这一点。在我的示例中,该方法将返回结果的array
Method objTest = WebElement.class.getMethod(strMethod, CharSequence[].class);