简体   繁体   中英

How to use @FindBy annotation in Selenium for span text?

I want to know what can I do to get the "Apple" text in span element with @FindBy annotation.

Thats html code:

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

and I tried something like that:

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

but it didn't work!

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; 

You can try with xpath stated below

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

You can use @FindBys like a chained element look-up

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

Or try using below:

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

or

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

Hopefully it resolves your issue.

你好,上述解决方案部分解决了我的问题,我有多个具有相同类的按钮,在不同文本的跨度中,如何在上面的代码中添加文本与硒 java 中的 Xpath 对我来说这是行不通的 @FindBy(how= How.XPATH,using="//span[@class='mat-button-wrapper' and text()='North America']")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM