Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Given a (python) selenium WebElement can I get the innerText?

The following

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

find me my element (a div that ONLY contains some text), but:

element.text

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

$('.theelementclass').text  # also (consistently) empty
$('.theelementclass').innerText  # YES! gets the div's text.

So, my question is, 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 its useful (since 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>
like image 611
user48956 Avatar asked May 13 '15 01:05

user48956


People also ask

How do I get innerText in Selenium?

getText() Method in Selenium This method helps retrieve the text, which is basically the innertext of a WebElement. getText() method returns string as a result. It removes the whitespaces if present in the front and back of the string.

How can we get a text of Webelement?

We can get the text from a website using Selenium webdriver USING the getText method. It helps to obtain the text for a particular element which is visible or the inner text (which is not concealed from the page).


2 Answers

Here is a more simple 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 get_attribute() method.

like image 172
Ali Sajjad Avatar answered Oct 14 '22 00:10

Ali Sajjad


You can pass webelement to js code

element = driver.find_element_by_css_selector('.theelementclass')
inner_text= driver.execute_script("return arguments[0].innerText;", element)
like image 30
Furious Duck Avatar answered Oct 14 '22 00:10

Furious Duck