java - 如何对 webelement 的子元素使用页面对象工厂框架

标签 java selenium selenium-webdriver webdriver pageobjects

我有一个搜索结果页面,其中包含许多作为搜索结果生成的产品项目。我可以获得产品 list 。 但价格、折扣、运费等产品详细信息作为子元素包含在这些 web 元素中。如何使用页面对象工厂模型通过使用@FindBy注释自动获取这些子元素的值。

目前我不知道如何获取它们,因此我通过在 findElement(By) 函数中显式提供父 WebElement 的上下文而不是 POF 的自动机制来显式获取它们。问题是如何将上下文设置为 WebElement 而不是 PageObject 类的驱动程序对象。我无法找到任何可以理解的网络文章来解释如何做到这一点。有人可以通过一个例子解释一种简单的方法吗?我将非常感激。 下面是解释测试类和代表产品的类的代码。

public class TestProducts {

.....
 //I can get the list of products from a 
 List<WebElement> we_prod_box_list = driver.findElements(By.xpath("//div[@id='content']/descendant::div[starts-with(@class,'product_box_container')]"));
.....
}

public class ProductItem {

private WebDriver driver = null;
private Actions action = null;
private WebElement we_prod_box = null;

public String we_prod_box_title = "";
public WebElement we_pt = null;
public String slideImgTitle = "";
public String oldPrice = "";
public String oldPriceTitle = "";
public String subPrice = "";
public WebElement we_purch_disc = null;
private WebDriverWait wait = null;
public String shippingText = "";
public String shippingCost = "";
public String discPrice = "";
    .....

    we_pt = we_prod_box.findElement(By.xpath(".//div[contains(@class, 'subcategor_price_tag')]"));
slideImgTitle = we_pt.findElement(By.xpath(".//div[contains(@class, 'subcategor_slideimgtitle')]")).getText();
oldPrice = we_prod_box.findElement(By.xpath(".//div[contains(@class, 'oldprice')]")).getText();
oldPriceTitle = we_prod_box.findElement(By.xpath(".//div[contains(@class, 'oldprice')]")).getAttribute("title");
subPrice = we_prod_box.findElement(By.xpath(".//span[contains(@class, 'sub-price')]")).getText();
     ......
}

最佳答案

通过使用@FindBy,您可以将包含产品项属性的 4 个 Web 元素放入 4 个不同的列表中。只需将这些元素的完整 xpath 传递给 FindBy 即可。 您可以迭代列表以获取单个值来测试或创建产品项对象等...

关于java - 如何对 webelement 的子元素使用页面对象工厂框架,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38987538/

相关文章:

java.lang.NoSuchFieldException

java - 监听器的代码执行顺序

python - 使用 Python 和 Selenium 进行网页抓取

java - 无法在 Maven 中使用 Selenium 连接到二进制 FirefoxBinary

c# - 在 selenium/webdriver c# 中循环遍历多个 moveToElement

java - 使用 Apache Axis2 从 WSDL 文件生成单独的 Java 文件而不是单个 stub

java - 如何解决子模块中的 Gradle Dependency 不一致?

java - 使用 ExpectedConditions 类断言元素不存在

ruby - 错误 : disable image loading on watir with firefox

python - selenium 无法使用方法 : cannot find elements by id, css_selector、xpath、链接文本定位元素