Skip to content
Advertisement

Get the text from parent element only (without text from children elements) using Selenium in Python?

Trying to get the number “6” from this html:

<div color="pain" class="sc-fAyiZu hNLuuN">
    <svg width="15" height="12" viewBox="0 0 15 12" fill="#7c82cb" data-testid="increase" color="pain" class="sc-jMZWZw iQTebp">
    <path d="M9.05 11.95a1 1 0 00.71-.29l4.95-4.95a1 1 0 00.2-.3A1 1 0 0015 6a1 1 0 00-.07-.36 1 1 0 00-.2-.3l-4.97-5a1 1 0 10-1.42 1.42L11.59 5H1a1 1 0 000 2h10.59l-3.25 3.24a1 1 0 00.71 1.71z"></path>
    </svg>
    6
    <div class="sc-bIaGYP cHxEYS">
    Text 2
    </div>
    </div>

Using this Selenium code:

element = WebDriverWait(driver, 40).until(
            EC.element_to_be_clickable((By.XPATH, xpathToElement)))

        element = driver.find_element_by_xpath(xpathPain).text

Getting the result from element:

"6
Text 2"

I.e. both the parent and the child elements text.

Advertisement

Answer

Try this xpath : .//div[@class=’sc-fAyiZu hNLuuN’].getAttribute(“innerText”).split(“”)[0]

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement