0

I am trying to extract the population figure/text of an element.

I tried with parent but its showing error. I am trying to get the Population of China from this page table https://en.wikipedia.org/wiki/China

Code trial:

WebElement dateBox7 = driver.findElement(By.xpath("//*[contains(text(),'Population')]/parent::tr//td/a[text()]"));

Error:

Exception in thread "main" org.openqa.selenium.NoSuchElementException:

I have tried //*[contains(text(),'2016 estimate')]/ancestor::tr/td/text()[1] this xpath it's showing the population in DOM.But in selenium it's showing error:

Exception in thread "main" org.openqa.selenium.InvalidSelectorException: invalid selector: The result of the xpath expression "//*[contains(text(),'2016 estimate')]/ancestor::tr/td/text()[1]" is: [object Text]. It should be an element.

Why it's not working?

undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
ashik
  • 99
  • 1
  • 7

2 Answers2

1

Try with this xpath

"//*[contains(.,'Population')]/parent::tr//th/a[text()]"

Note there are two changes: td -> th, and [contains(text(),'Population')] -> [contains(.,'Population')].

When searching for [contains(.,'Population')] the "dot" means searching all text inside of the element (including the descendants) while "text()" will search only for the direct textural content of the element.

EDIT:

Based on your comment, try this xpath:

"//*[contains(.,'Population')]/parent::tr/following-sibling::tr[1]/td"

EDIT #2:

For a tutorial on Xpath locators, see here and for a free course on the topic see here.

Mate Mrše
  • 7,997
  • 10
  • 40
  • 77
  • but it's not showing the population of china 1,403,500,365.I tried this //*[contains(text(),'2016 estimate')]/ancestor::tr/td/text()[1] But showing error i described in post comment section. – ashik May 28 '19 at 10:06
  • Ah, I see. You are looking at the wrong element. I'll give you the right xpath soon. – Mate Mrše May 28 '19 at 10:07
1

To extract the the Population of China i.e. the text 1,403,500,365 from this page table https://en.wikipedia.org/wiki/China you need to induce WebDriverWait for the visibilityOfElementLocated() and as the desired text is within a Text Node you need to use executeScript() and you can use the following Locator Strategy:

WebElement myElement = new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//a[text()='Population']//following::tr[1]//td"))); 
System.out.println(((JavascriptExecutor)driver).executeScript("return arguments[0].childNodes[2].textContent;", myElement).toString());

You can find a similar discussion in How to retrieve text from an element using Selenium WebDriver and Java

undetected Selenium
  • 183,867
  • 41
  • 278
  • 352