Java 硒动态定位器
我的问题是关于动态定位器。 我的页面类通常如下所示:Java 硒动态定位器,java,selenium,selenium-webdriver,Java,Selenium,Selenium Webdriver,我的问题是关于动态定位器。 我的页面类通常如下所示: public class MyPage { private WebDriver driver; private By myFixedLocator = By.xpath("......."); private String myDynamicLoactor = "//div[@id = 'someId']" + "//div[contains
public class MyPage {
private WebDriver driver;
private By myFixedLocator = By.xpath(".......");
private String myDynamicLoactor = "//div[@id = 'someId']" +
"//div[contains( @class, '<className>')]";
public MyPage(WebDriver driver) {this.driver = driver;}
public AnotherSuperPage getAnotherPage(String className) {
By tmpBy = By.xpath(myDynamicLocator.replace("<className>", className));
driver.findElement(tmpBy);
return new AnotherSuperPage(driver);
}
//for example here: childOne and Two are sub classes of AnotherSuperClass
public AnotherChild1Page getChildOne() {return getAnotherPage("childOne");}
public AnotherChild1Page getChildTwo() {return getAnotherPage("childTwo")}
}
公共类MyPage{
私有网络驱动程序;
myFixedLocator私有=通过.xpath(“…”);
私有字符串myDynamicLoactor=“//div[@id='someId']”+
//div[包含(@class,)];
公共MyPage(WebDriver驱动程序){this.driver=driver;}
public AnotherSuperPage getAnotherPage(字符串类名称){
By tmpBy=By.xpath(mydynamiclocotor.replace(“,className));
驱动程序文件(tmpBy);
返回新的另一个超级页面(驱动程序);
}
//例如:childOne和Two是另一个超类的子类
public AnotherChild1Page getChildOne(){return getAnotherPage(“childOne”);}
public AnotherChild1Page getChildTwo(){return getAnotherPage(“childTwo”)}
}
像myDynamicLocator这样的定位器表示元素,它们都具有类似的xpath结构,只有一个字符串部分除外。
有没有更好的办法?据我所知,By定位器是最终的且不可修改的。
这也是我不使用页面工厂的原因,因为@FindBy注释可以使用灵活的定位器,如上面的示例所示。
当我有一个By定位器时,我能以一种平滑的方式得到里面的文本吗?因为By.toString()提供了全部信息,包括“xpath”…您也可以通过以下方式实现:
public AnotherSuperPage getAnotherPage(String className) {
driver.findElement(By.xpath("//div[@id = 'someId']//div[contains( @class, '" + className +"')]"));
return new AnotherSuperPage(driver);
}
而不是创建一个字符串对象,然后替换它并将其存储在另一个变量中,尽管这是内部发生的事情,但编码较少。希望我对你的理解是正确的…你对我的理解是正确的。问题是,这一切都与编程风格有关。我宁愿将我的所有定位器作为字段放在类顶部,而不是在方法内部定义,因为有时我需要它们作为其他更大的loactor的一部分(例如,我有一个表的定位器,而不是将此定位器用作同一表行的定位器的一部分)。我想知道的唯一一件事是,是否有一种方法可以将它们放置为字段,并且仍然不定义字符串,而是定义一个灵活的可变字段。显然不是。。。