Why text, innerText, innerHTML return empty in selenium

Viewed 1445
<div class="SdTitle-sc-iwgcvh dmugDV title">#24 Information Revolution</div>

I want to get the text in this div. I was using this code:

title = driver.find_element_by_xpath("/html/body/div/div[2]/div[4]/div/div[2]/div[1]/div/div[1]").get_attribute("innerText")

But it returns an empty string, I tried text(), get_attribute("innerText"), get_attribute("innerHTML"). None of them works.

The element can be found by selenium. I also found this element with the xpath in chrome, which means the xpath is correct.

If I tried get_attribute('outerHTML'), it returns

<div class="SdTitle-sc-iwgcvh dmugDV title"></div>

This is so strange.

I searched on Chrome that the div with these classes only has 1.

Thank you for your help.

4 Answers

you are using text() instead of .text

There is no such thing called get_attribute("innerText")

Update 1 :

el = WebDriverWait(driver, 10).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "div[class^='SdTitle']"))).text
print(el)

The attribute is called innerHTML Read here for more details: https://www.w3schools.com/jsref/prop_html_innerhtml.asp

el = driver.find_element_by_css_selector(".SdTitle-sc-iwgcvh.dmugDV.title").text
el = driver.find_element_by_css_selector(".SdTitle-sc-iwgcvh.dmugDV.title").get_attribute("innerHTML")

Print to check the output. A little explanation: . is used for a class name. If there are few classes in a one html tag, you can make a locator of them divided by dot, without spaces.

Try this

driver.find_element_by_xpath(".//div[@class='SdTitle-sc-iwgcvh dmugDV title']").get_attribute("innertext")

If not use text to get the text value from the element like this

driver.find_element_by_xpath(".//div[@class='SdTitle-sc-iwgcvh dmugDV title']").text

Similar issue, I found in Protractor. I too, used different ways to get the text using .getText(), innerText, innerHtml etc. But finally I tried to use tagName locator to retrieve the text. Might be below code is helps to you to implement in Selenium. Note: Below code is for Protractor

element(by.tagName('mat-chip')).getText().then(function (rowAtt) {
                console.log("Attributed Under Row Group-"+rowAtt)
                expect(rowAtt).toBe(attValues.explore.attributeValues.rowAttributes[i], 'Attribute value is not matching');
                if (rowAtt) {
                    exploreModule.attributeCheckBox().click();
                } else {
                    console.log("attribute checkbox is not present");
                }
            })
Related