0

I'm trying to get text of a div, without getting text of the child span, here is my html :

  <div class="Travel">
  
    <!--ko text: marketName-->Résultat<!--/ko-->

    <span class="label">Cities</span>

  </div>

I want to get Résultat, Instead I get Résultat Cities

here is what I tried :

//div[@class='Travel']//text()
DebanjanB
  • 118,661
  • 30
  • 168
  • 217
dxtr
  • 609
  • 1
  • 7
  • 14

2 Answers2

1

For Python use this -

Direct Div text -

driver.find_element_by_xpath('//div[@class="Travel"]').text()

Div text through span tag -

driver.find_element_by_xpath('//span[text()="Cities"])/parent::div').text()

For Java use this -

Direct Div text -

driver.findElements(By.xpath('//div[@class="Travel"]')).getText();

Div text through span tag -

driver.findElements(By.xpath('//span[text()="Cities"])/parent::div')).getText();

Swaroop Humane
  • 1,291
  • 1
  • 4
  • 15
1

The text Résultat is within a text node. So extract the text you can use either of the following Locator Strategies:

  • Using , and childNodes:

    System.out.println(((JavascriptExecutor)driver).executeScript('return arguments[0].childNodes[2].textContent;', driver.findElement(By.xpath("//div[@class='Travel']"))).toString());
    
  • Using , and get_attribute("innerHTML"):

    print(driver.find_element_by_css_selector("div.Travel").get_attribute("innerHTML").splitlines()[2])
    
DebanjanB
  • 118,661
  • 30
  • 168
  • 217