Techchamp Pgm
Techchamp Pgm

Reputation: 159

How to retrieve the label text as per the html provided?

Sometimes I failed to get the inner text of a web-element; recently working on thePersonal insurance, and failed to get inner text of label (web element). Here are the script and screenshot of webpage inspected:

WebElement detailPostCode =driver.findElement(By.xpath("//label[@for='q_codePostalDetailAU']"));
System.out.println("postcode label text "+detailPostCode.getText());

Could any please help me understand the problem. Thank you for your kind concern.

screenshot of the page-inspection view of the webelement

Upvotes: 0

Views: 2112

Answers (2)

undetected Selenium
undetected Selenium

Reputation: 193188

As per the HTML you have shared the <label> with text as Postal code is a child node of the <div> tag with class attribute as q_codePostal.

What went wrong?

As per your code trial you have used:

WebElement detailPostCode = driver.findElement(By.xpath("//label[@for='q_codePostalDetailAU']"));

In this expression //label[@for='q_codePostalDetailAU'] will always refer to the descending <input> tag with id attribute as q_codePostalDetailAU. Hence your code trial didn't work.

Solution

As an alternative you can use the following solution:

WebElement detailPostCode = driver.findElement(By.cssSelector("div.q_codePostal>label"));

Upvotes: 1

mbn217
mbn217

Reputation: 914

Can you try this xpath:

driver.findElement(By.xpath("//div[@class='q_codePostal']/label"));

Upvotes: 0

Related Questions