如何解决Java Selenium自定义方法获取Webelement的名称作为参数
在我的项目中使用Java Selenium和Page Object,想要创建一个自定义方法,该方法将获取两个字符串作为参数,将它们组合并调用正确的webelement来执行一些操作。
下面是我的Page对象的示例
public class Test extends Base {
public Test() {
PageFactory.initElements(driver,this);
}
@FindBy(xpath = "//div[@id='question1No']")
WebElement question1Yes;
@FindBy(xpath = "//div[@id='question1No']")
WebElement question1No;
public Object GetField(String answer,String question) {
Field field = null;
try {
field = Test.class.getField((question+answer).replace("\"",""));
return field.get(this);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public void answerQuestion(String answer,String question) {
WebElement element = (WebElement)GetField(answer,question);
element.click();
}
并调用该方法,例如:
answerQuestion("Yes","question1")
调用此方法应在question1Yes元素上单击。
解决方法
您可以使用反射。
Field field = Test.class.getField("question1Yes");
WebElement element = (WebElement) field.get(this);
然后您可以使用WebElement进行任何操作
upd。
如果字段是私有的,则写field.setAccessible(true);
添加到以上答案中,根据OP需求以及软件包名称对其进行更新
import java.lang.reflect.Field;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
public class Test extends base{
@FindBy(xpath = "//div[@id='question1No']")
public WebElement question1Yes;
@FindBy(xpath = "//div[@id='question1No']")
public WebElement question1No;
public Test() {
PageFactory.initElements(driver,this);
}
public void answerQuestion(String answer,String question) {
WebElement temp = null;
try {
Field field = Test.class.getField(question + answer);
temp = (WebElement) field.get(this);
temp.click();
} catch (Exception e) {
// Handle the exception here when there is wrong field
// throws NoSuchFieldException,SecurityException
e.printStackTrace();
}
}
}
您还可以使用通用方法获取字段
public Object GetField(String answer,String question) {
Field field = null;
try {
field = Test.class.getField(question + answer);
return field.get(this);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
这样您的代码就会像
import java.lang.reflect.Field;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
public class Test extends base {
@FindBy(xpath = "//div[@id='question1No']")
public WebElement question1Yes;
@FindBy(xpath = "//div[@id='question1No']")
public WebElement question1No;
public Test() {
PageFactory.initElements(driver,String question) {
WebElement temp = (WebElement)GetField(answer,question);
temp.click();
}
public Object GetField(String answer,String question) {
Field field = null;
try {
field = Test.class.getField(question + answer);
return field.get(this);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。