我正在自动化https://www.zoho.com/login.html 。此页面在框架内有登录部分。当我切换不同的框架并搜索我的电子邮件/电话字段(登录部分)时,我可以找到它,然后使用工作 block (如下),但不能使用类似的代码(也在下面),这是两个 block 之间的唯一区别这就是我识别我的 userNameInputBox 元素的方式。
//这是工作
List<WebElement> iframeElements = driver.findElements(By.tagName("iframe"));
int nFrames = iframeElements.size();
//Switching frame to go to login frame
for (int i=0; i<=nFrames ; i++) {
System.out.println("nFrames: " +nFrames);
driver.switchTo().frame(i);
if (driver.findElement(By.name("lid")).isDisplayed()){
driver.findElement(By.name("lid")).sendKeys("myuserName1");
}}
但是,如果我使用这个(下面的代码),它不起作用,而是在我单击我的 userNameInput 进入用户名字段的行中给出 NullPointerException 。
///这不起作用
//Elements
@FindBy(name="lid")
WebElement userNameInput;
//Switching frame to go to login frame
for (int i=0; i<=nFrames ; i++) {
System.out.println("nFrames: " +nFrames);
driver.switchTo().frame(i);
if (driver.findElement(By.name("lid")).isDisplayed()){
userNameInput.click(); //clicking the inputBox
userNameInput.sendKeys("myuserName"); //Sendingkeys into
}}
有人可以解释一下这种异常的原因是什么吗?或者指出我错过了什么?我想对 WebElement 使用 @FindBy。
最佳答案
@FindBy
标记旨在与页面对象模型配合使用。要使用它,您必须使用 PageFactory 初始化页面对象,以便初始化字段,然后由网络驱动程序“找到”。
参见https://github.com/SeleniumHQ/selenium/wiki/PageFactory有关它的文档。
因此,在尝试使用 userNameInput
字段之前,您必须拥有某种类似
PageFactory.initElements(驱动程序,页面);
(其中 page
var 是使用 @FindBy
注释的类。
关于java - 使用@FindBy和By的区别;这个错误的原因可能是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43686756/