如何在Selenium中使用@FindBy注释来查找span文本?

时间:2017-12-18 00:36:51

标签: java maven selenium findby

我想知道如何才能获得#34; Apple"带有@FindBy注释的span元素中的文本。

这就是HTML代码:

<span class="ui-cell-data">Apple</span>

我试过这样的事情:

@FindBy(className = "ui-cell-data:Samsung")
WebElement customerName;

但它没有用!

3 个答案:

答案 0 :(得分:2)

As per the HTML you have shared you may/maynot have been able to get the Apple text within the span element with :

@FindBy(className = "ui-cell-data")
WebElement customerName;

Your code was nearly perfect but the trailing part in the className as :Samsung was unnecessary.

But again, looking at the class attribute it is expected that a couple of more <span> tags will have the same class. So to uniquely identify the intended WebElement we need to refer to a parent node and follow its decendents to reach this particular node.

Finally, with the given HTML the following code block will be much cleaner :

  • cssSelector

    @FindBy(cssSelector = "span.ui-cell-data")
    WebElement customerName;
    
  • xpath

    @FindBy(xpath = "//span[@class='ui-cell-data']")
    WebElement customerName;
    

答案 1 :(得分:1)

You can try with xpath stated below

 @FindBy(xpath = "//span[@class = 'ui-cell-data']") 
 private WebElement element;

答案 2 :(得分:0)

您可以像链式元素查找一样使用@FindBys

@FindBys({@FindBy(className = "ui-cell-data")})
private WebElement element;

或尝试使用以下内容:

@FindBy(xpath = "//*[@class = 'ui-cell-data']")
private WebElement element;

@FindBy(css = ".ui-cell-data")
private WebElement element; 

希望它可以解决您的问题。