gpt4 book ai didi

java - 尝试在 webDriver 中使用 @FindBy 时出现 java.lang.NullPointerException

转载 作者:行者123 更新时间:2023-11-30 07:58:05 25 4
gpt4 key购买 nike

当我尝试使用 @FindBy 注释查找网页上的元素时,出现 java.lang.NullPointerException。

我的代码 -

public class pageObject{
WebDriver driver;

@FindBy(id = "email")
WebElement searchBox;
@FindBy(id = "u_0_v")
WebElement submit;

void pageObject(String web){
FirefoxProfile profile = new FirefoxProfile();
profile.setAssumeUntrustedCertificateIssuer(false);
profile.setAcceptUntrustedCertificates(false);
this.driver = new FirefoxDriver(profile);
this.driver.get(web);
this.driver.manage().window().maximize();
this.driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
searchBox.click();
searchBox.sendKeys("er");
submit.click();
}

public static void main(String[] args){
new pageObject("https://www.facebook.com/?_rdr=p");
}
}

上面的代码有一个异常(exception) -

异常-

Exception in thread "main" java.lang.NullPointerException
at com.Selenium_Practice.pageObject.<init>(pageObject.java:29)
at com.Selenium_Practice.pageObject.main(pageObject.java:35)

我也尝试过使用

 @FindBy(how = HOW.ID , using = "email")  and @FindBy(how = HOW.ID , using = "u_0_v")

但再次遇到相同的空指针异常

最佳答案

如果您使用 Selenium 的 PageFactory 并且希望您的类是自包含的,您首先需要初始化您的 Elements*

pageObject(String web){

FirefoxProfile profile = new FirefoxProfile();
profile.setAssumeUntrustedCertificateIssuer(false);
profile.setAcceptUntrustedCertificates(false);
this.driver = new FirefoxDriver(profile);

// You need to put this line in your constructor
PageFactory.initElements(this.driver, this);

// Then follows the rest of your constructor
...
}

* 的意思是,您也可以在类外部初始化此类元素,但我认为您想在类内部执行此操作。

关于java - 尝试在 webDriver 中使用 @FindBy 时出现 java.lang.NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32375047/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com