问题:给定一个 (python) selenium WebElement 我可以得到 innerText 吗?

以下

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

找到我的元素(一个只包含一些文本的 div),但是:

element.text

返回一个空字符串(这是一个惊喜)。从 Java 脚本控制台:

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

所以,我的问题是,鉴于我有一些 WebElement,我能找到 innerText 吗? (出于无聊的原因,我想使用找到的 web 元素进行操作,而不是原始查询)。

我包括周围的 HTML。但是,我认为它没有用(因为找到了元素并且是唯一的)

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

解答

这是一个更简单的方法:

element = driver.find_element_by_class_name('theelementclass')
text = element.get_attribute('innerText')

因此,您可以使用 get_attribute() 方法对 'outerHTML'、'href'、'src' 等进行类似的操作。

Logo

Python社区为您提供最前沿的新闻资讯和知识内容

更多推荐