1

I have the opposite problem described here. I can't get the text more than one layer deep.

HTML is structured in the following manner:

    <span class="data">
        <p>This text is extracted just fine.</p>
        <p>And so is this.</p>
        <p>
            And this.
            <div>
                <p>But this text is not extracted.</p>
            </div>
        </p>
        <div>
            <p>And neither is this.</p>
        </div>
    </span>

My Python code looks something like this:

    el.find_element_by_xpath(".//span[contains(@class, 'data')]").text

3 Answers3

0

Try the same with child elements:

print(el.find_element_by_xpath(".//span[contains(@class, 'data')]").text)
print(el.find_element_by_xpath(".//span[contains(@class, 'data')]/div").text)
print(el.find_element_by_xpath(".//span[contains(@class, 'data')]/p").text)
Krzy
  • 83
  • 7
0

Not sure what's the referred el in your original post. But able to get all the text using the below.

 driver.find_element_by_xpath("//span[@class='data']").text

Output:

'This text is extracted just fine.\nAnd so is this.\nAnd this.\nBut this text is not extracted.\nAnd neither is this.'

supputuri
  • 13,644
  • 2
  • 21
  • 39
0
  1. Instead of relying on WebElement.text property consider querying innerText property
  2. Consider using Explicit Wait as it will make your test more robust and reliable in case if the element you're looking for is loaded by i.e. AJAX call

Assuming all above:

print(WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, "//span[@class='data']"))).get_attribute("innerText"))

Demo:

enter image description here

Dmitri T
  • 159,985
  • 5
  • 83
  • 133