Selenium 页面模型 - 如何获取属性、提取其内​​容并在另一个类中使用它

问题描述

我想知道是否有可能获取位于 DOM 中的属性的内容并将其作为变量存储在 java 类中来自 Selenium 的 PageFactory (@FindBy)。 然后,我需要在与同一网站(页面对象模型)上的另一个页面相对应的另一个类中使用此变量。 有人可以提供一些例子和方法吗? 我没有任何代码可以展示。我只是想知道这在技术上是否可行以及如何实现。

----编辑 1---- 根据要求,一些代码来解释。 下面是DOM中的属性

<label id="HouseNumberVersion">HOUSE N° x </label>

例如,我使用 Selenium 的 PageFactory 找到 DOM 的这个元素并获取其内容;遵循 POM 方法(这就是它被称为 Page1 的原因)

    
public class Page1 {  

 WebDriver driver;
   
 @FindBy (xpath="//*[@id="HouseNumberVersion"]")
   WebElement houseNumber;
  
 public Page1(WebDriver driver){
    PageFactory.initElements(driver,this);
    this.driver = driver;
 }

 public Page1(){
}

 public void assertEquals(){
   String actual = houseNumber.getAttribute("innerHTML");
   //some code here to assert this is equal
   // to another string but not this method is not needed it's just to show that
   // i can use this string in this page properly using this method
 }
 
 public String getHouse(){
  String actual = houseNumber.getAttribute("innerHTML");
  return actual;
}
    
}

现在我想在我的另一个类中调用和使用字符串 actual ,它对应于网站中的另一个页面。

public class Page2 {  

 WebDriver driver;
 
 //i search for an element in this second page which is an input  
 @FindBy (xpath="//*[@id="HouseInput"]")
     WebElement houseInput;
 
 public Page2(WebDriver driver){
    PageFactory.initElements(driver,this);
    this.driver = driver;
 }

 public void sendActualToInput(){
   
  // i created an object to recover the string within the return method in
  // Page1
  Page1 p = new Page1();
  String number = p.getHouse(); 
  //i send this string recovered from the other 
  // to another string
  houseInput.sendKeys(number);
 }
    
}

我最终在主测试脚本中调用 Page2 中的方法 sendActualToInput 如下


public class MyTest (){

 public WebDriver driver;
 // some Before Method here ..

 @Test
 Public  void CheckHouse(){
  Page2 p2Object = new Page2(driver);
  p2Object.sendActualToInput();
  //some others actions here..
 }

}

我试过了,但出现错误 java.lang.NullPointerException。 Eclipse 控制台指的是行 String actual = houseNumber.getAttribute("innerHTML"); Page2 中的 sendActualToInput 方法似乎没有返回任何内容。因为如果我在这个方法中加入一个 sysout sendActualToInput 它会在控制台中打印这个 sysout 的内容。

是否可以管理?

------EDIT2--------

我已经在我的代码中初始化了我的字段。我只是忘了在代码片段中添加它们,但现在初始化函数在代码中。问题仍在发生。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)