【问题标题】:Given a (python) selenium WebElement can I get the innerText?给定一个(python)selenium WebElement,我可以得到 innerText 吗?
【发布时间】:2015-05-13 01:18:00
【问题描述】:

以下

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>

【问题讨论】:

  • 你能添加你试图从中获取文本的 HTML 吗?
  • 它是否适用于 element.get_attribute('innerText')?您也可以尝试使用 element.get_attribute('innerHTML')。您使用的是什么浏览器驱动程序(firefox、chrome 等)?

标签: python selenium webdriver


【解决方案1】:

这里有一个更简单的方法:

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

所以你可以用 get_attribute( ) 方法。

【讨论】:

  • Bravo 推荐使用提供的方法。
【解决方案2】:

你可以将webelement传递给js代码

element = driver.find_element_by_css_selector('.theelementclass')
inner_text= driver.execute_script("return arguments[0].innerText;", element)

【讨论】:

【解决方案3】:

innerText 特定于 IE。如果你想要一个跨平台的字段,请使用textContent

driver.execute_script("return arguments[0].textContent", element)

element 是一个已经获得的WebElement

顺便说一句,你说你在控制台上试过这个:

$('.theelementclass').text

它不起作用,因为.text 是一个函数。它必须被调用。

【讨论】:

  • 我收到selenium.common.exceptions.WebDriverException: Message: unknown error: attributes is not defined
  • @etayluz 我的意思是输入arguments,而不是attributes。现在已修复。感谢您的评论!
猜你喜欢
  • 2019-12-13
  • 2012-01-18
  • 1970-01-01
  • 1970-01-01
  • 2012-08-01
  • 2011-04-06
  • 2012-09-08
  • 1970-01-01
  • 2019-07-18
相关资源
最近更新 更多