-2

I want to retrieve text Effective Date from the below image. How to write xpath for this?

Snapshot of the HTML:

enter image description here

DebanjanB
  • 118,661
  • 30
  • 168
  • 217
Suma
  • 93
  • 10

3 Answers3

0

It is possible, however I would try to do it with CSS.

With XPath:

String spanText= driver.findElement(By.xpath(
                   "//*[@class='yourDiv']/.//span[contains(@id,'yourLabel')]"))
              .getAttribute("innerHTML");

With CSS:

String spanText = driver.findElement(By.cssSelector("#IdOfDiv span.selectLabel"))
              .getAttribute("innerHTML");
AztecCodes
  • 29
  • 5
0

The text Effective Date is within a text node. So to retrieve the text you have to induce WebDriverWait for the visibilityOfElementLocated() and you can use either of the following Locator Strategies:

  • cssSelector:

    System.out.println(((JavascriptExecutor)driver).executeScript("return arguments[0].lastChild.textContent;", new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("table.data_form.label tbody > tr > th")))).toString());
    
  • xpath:

    System.out.println(((JavascriptExecutor)driver).executeScript("return arguments[0].lastChild.textContent;", new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//table[@class='data_form label']//tbody/tr/th")))).toString());
    
DebanjanB
  • 118,661
  • 30
  • 168
  • 217
0

With Selenium, I usually prefer to use the id locator when it is available. In this case, for your target element, there is no id. My next option would be to see if I can use the name property which is also not available here. So I usually use xpath as my last choice, not that it is not good but is slow. However xpath is usually very capable, you can almost locate anything with it. In your case, here is the locator I would use:

String elementLocator = "//span[@id='rightmandatory']/parent::th";
String text = driver.findElement(By.xpath(elementLocator)).getText();

If the getText() method reads the text from the span element, then you can alternatively replace it with .getAttribute("innerHTML"). Of course, there are other locators that you can use here, but you ask for the xpath. I hope this helps.

pdrersin
  • 276
  • 3
  • 10