17

The following

element = driver.execute_script("return $('.theelementclass')")[0]

finds me my element (a div that only contains some text), but:

element.text

returns an empty string (which is a surprise). From the JavaScript console:

$('.theelementclass').text  // Also (consistently) empty
$('.theelementclass').innerText  // YES! Gets the div's text.

Given that I have some WebElement, can I find the innerText? (For boring reasons, I want to operate with a found webelement, not the original query.)

I'm including the surrounding HTML. However, I don't think it's useful (since the element is found and is unique).

<first-panel on-click="onClickLearnMore()" class="ng-isolate-scope">
  <div class="comp-onboarding-first-thought-panel">
    <div class="onboarding-text-container">
      <div class="theelementclass">
        Congratulations.
        You found the text is here!
      </div>
      <div class="button-cont">
        <div ng-click="onClickButton()">Learn more about The Thing</div>
      </div>
    </div>
  </div>
</first-panel>
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
user48956
  • 14,850
  • 19
  • 93
  • 154
  • Can you add the HTML you're trying to get the text from? – Richard May 13 '15 at 01:42
  • 1
    does it works with element.get_attribute('innerText')? you can also try with element.get_attribute('innerHTML'). what browser driver are you using (firefox, chrome, etc)? – dnlcrl May 13 '15 at 08:50

3 Answers3

23

Here is a simpler approach:

element = driver.find_element_by_class_name('theelementclass')
text = element.get_attribute('innerText')

So you can do similar stuff with 'outerHTML', 'href', 'src', etc. with the get_attribute() method.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Ali Sajjad
  • 3,589
  • 1
  • 28
  • 38
4

You can pass an webelement to JavaScript code:

element = driver.find_element_by_css_selector('.theelementclass')
inner_text = driver.execute_script("return arguments[0].innerText;", element)
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Furious Duck
  • 2,009
  • 1
  • 16
  • 18
2

innerText is specific to Internet Explorer. If you want a cross-platform field, use textContent:

driver.execute_script("return arguments[0].textContent", element)

element is an already obtained WebElement.

By the way, you said you tried this at the console:

$('.theelementclass').text

It won't work, because .text is a function. It has to be called.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Louis
  • 146,715
  • 28
  • 274
  • 320
  • I'm getting `selenium.common.exceptions.WebDriverException: Message: unknown error: attributes is not defined` – etayluz Dec 15 '18 at 08:40
  • 1
    @etayluz I meant to type `arguments`, not `attributes`. It is fixed now. Thank you for the comment! – Louis Dec 15 '18 at 19:38