How to get text from web page?

Hi There,
I need to get text from web page and then it will be stored in to excel.

I have div element likes below:

<div class="heading-middle">
       <h1 class="margin-bottom-s">Hamid, Tarmizi</h1>                      
 </div>

I want to grab “Hamid, Tarmizi”, this text is dinamyc and will be changed according who is current loging in.

And css as below:

@media (min-width: 1200px)
h1, .h1 {
     font-size: 96px;
     line-height: 84px;
}

Thanks in advance,

Tarmizi

hi,

try this

@Timo_Kuisma1 WebUI.getAttribute() will not work here.

@tarmizi2001 You should use WebUI.getText() which will retrieve the innerText of a selector.

Based on the HTML you posted, this CSS selector will target the relevant <div> element:

div.heading-middle > h1.margin-bottom-s
1 Like

hi,

ouh, sorry wrong paste :smile:

Use GetElementText from the Element. And if you want to verify the text matches the expected result, you can add another test step - VerifyMatch

Hi,
@Russ_Thomas
@Timo_Kuisma1

Thanks very much for response. It still doesn’t work.
Here are the actual html elements that I try to grab the text value:

<div style>
    <h2 class="p3 text-center margin-bottom-xl margin-bottom-sm-s" style="">
        WELCOME, Hamid, Tarmizi
    </h2>
</div>

And my latest script using web element:

WebDriver driver = DriverFactory.getWebDriver()
List list = driver.findElements(By.className(“p3 text-center margin-bottom-xl margin-bottom-sm-s”))
for(WebElement l : list){
print("print: "+l.getText())
}

No error but the list is empty.

Is there any way to get text using element class?

Thanks in advance,
Tarmizi

I don’t use those APIs and I’m too lazy to go look them up.

This guy on the other hand… @Brandon_Hein

My guess is that your list is empty, and it’s not a problem with getText(). Can you please print the size of your list to verify?:

WebDriver driver = DriverFactory.getWebDriver()
List list = driver.findElements(By.className(“p3 text-center margin-bottom-xl margin-bottom-sm-s”))
print(list.size())

Sorry, you’ve already stated that your list is empty… But again, this is not a problem with getText(), you are using it correctly. What you need is a proper locator to find that specific element. I generally use xpath to do this. I don’t know what the rest of your html looks like, but to get a list of <h2> elements and print them, it’s as simple as:

WebDriver driver = DriverFactory.getWebDriver()
List<WebElement> elements = driver.findElements(By.xpath("//h2"))
for(WebElement element : elements) {
    print("Heading text is: " + element.getText())
}

It worked.
Many thanks to all of you.

1 Like