Selenium Python,从节点和所有子节点提取文本

时间:2019-07-21 19:09:05

标签: selenium python-3.6

我遇到here所述的相反问题。我的文字深度不能超过一层。

HTML的结构如下:

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

我的Python代码看起来像这样:

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

3 个答案:

答案 0 :(得分:0)

对子元素尝试相同的操作

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)

答案 1 :(得分:0)

不确定原始帖子中引用的el是什么。但是可以使用以下内容获取所有文本。

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

输出:

  

'提取的文本很好。\ n这也是。\ n还有这个。\ n但是没有提取此文本。\ n这也不是。'

答案 2 :(得分:0)

  1. 考虑查询WebElement.text属性,而不是依靠innerText属性
  2. 考虑使用Explicit Wait,因为如果要查找的元素是通过AJAX调用
  3. 加载的,这将使您的测试更加健壮和可靠。

假设以上所有条件

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

演示:

enter image description here

相关问题