本文介绍了Selenium Webdriver:使用相对于其他元素的路径进行页面工厂初始化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用页面工厂 @FindBy 注释在Selenium Webdriver中编写页面对象。页面对象用于侧边栏,包含页面对象需要与之交互的所有元素的父WebElement以这种方式初始化:

I'm trying to write a page object in Selenium Webdriver using the page factory @FindBy annotations. The page object is for a sidebar, and the parent WebElement containing all elements the page object needs to interact with is initialized in this way:

@FindBy (xpath = "//div[contains(@class,'yui3-accordion-panel-content') and child::div[.='Sidebar']]")
WebElement sidebar;

然后我想要相对于这个侧栏的搜索输入元素。有没有办法引用侧栏元素?我可以将整个路径复制并粘贴到开头:

I then want the search input relative to this sidebar element. Is there a way to do this referencing sidebar element? I could copy and paste the entire path to the beginning:

@FindBy (xpath = "//div[contains(@class,'yui3-accordion-panel-content') and child::div[.='Sidebar']]//input[@id='search']")

但我宁愿相对于第一个元素。这样的事情可能吗?

But I'd much rather make it relative to the first element. Is anything like this possible?

@FindBy (parent = "sidebar", xpath = ".//input[@id='search']")

有点缺乏......

The Selenium documentation on the @FindBy annotation is a bit lacking...

推荐答案

回答我自己的问题。

答案是实现一个允许你的ElementLocatorFactory提供搜索上下文(意思是驱动程序或WebElement)。

The answer is to implement an ElementLocatorFactory that allows you to provide a search context (meaning, a driver or a WebElement).

public class SearchContextElementLocatorFactory
        implements ElementLocatorFactory {

    private final SearchContext context;

    public SearchContextElementLocatorFactory(SearchContext context) {
        this.context = context;
    }

    @Override
    public ElementLocator createLocator(Field field) {
        return new DefaultElementLocator(context, field);
    }
}

然后,在实例化页面对象时,使用此定位器工厂。

Then, when instantiating your page object, use this locator factory.

WebElement parent = driver.findElement(By.xpath("//div[contains(@class,'yui3-accordion-panel-content') and child::div[.='Sidebar']]"));
SearchContextElementLocatorFactory elementLocatorFactory = new SearchContextElementLocatorFactory(parent);
PageFactory.initElements(elementLocatorFactory, this);

现在你的 @FindBy 注释将是相对的到。例如,要获取主侧边栏 WebElement

Now your @FindBy annotations will be relative to parent. For example, to get the main sidebar WebElement:

@FindBy(xpath = ".")
WebElement sideBar;

这篇关于Selenium Webdriver:使用相对于其他元素的路径进行页面工厂初始化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-03 07:12