Search code examples
pythonseleniumwebdriver

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


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>

Solution

  • 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.