Selenium Webdriver: how to check text that is inside h2 and duplicated class

I want to find text in below HTML code but there are two duplicated classes.

<div id="header" class="cf">
<div class="cf">
<h1>
   <a href="/">Text</a>
</h1>

      

I found, but not sure if this is the best way to do it, because the text may appear somewhere else.

WebElement LL = driver.findElement(By.linkText("Text"));

      

Anyone have a better way to find this please? THANKS in advance!

+3


source to share


2 answers


Move on to the next css to identify the element more precisely. And id header

must be unique, and that should be enough to uniquely identify this element



By css = By.cssSelector("#header div.cf>h1>a");
WebElement element = driver.findElement(css );
String text = element.getText();

      

+1


source


You can use xpath as your selector and then use the WebElements method getText()

to extract the text.



WebElement element = driver.findElement(By.xpath(".//div[@class='cf']/h1/a"));
String text = element.getText();

      

0


source







All Articles