Given a (Python) Selenium WebElement, can I get the innerText?

Question:

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>
Asked By: user48956

||

Answers:

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)
Answered By: Furious Duck

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.

Answered By: Louis

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.

Answered By: Ali Sajjad
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.