如何在 Selenium WebDriver 中获取元素的文本,而不包含子元素文本? [英] How to get text of an element in Selenium WebDriver, without including child element text?
问题描述
这是一些<div id="b">text</div>
获得这是一些"并非易事.例如,这将返回这是一些文本":
driver.find_element_by_id('a').text
一般来说,如何获取特定元素的文本而不包括其子元素的文本?
(我在下面提供了一个答案,但会留下这个问题,以防有人能想出一个不那么可怕的解决方案).
这是一个通用的解决方案:
def get_text_ exclude_children(driver, element):返回 driver.execute_script("""返回 jQuery(arguments[0]).contents().filter(function() {返回 this.nodeType == Node.TEXT_NODE;}).文本();, 元素)
传递给函数的元素可以是从 find_element...()
方法获得的东西(即它可以是一个 WebElement
对象).
或者如果你没有 jQuery 或者不想使用它,你可以用这个替换上面的函数体:
return self.driver.execute_script("""var parent = 参数[0];var child = parent.firstChild;var ret = "";而(孩子){如果(child.nodeType === Node.TEXT_NODE)ret += child.textContent;child = child.nextSibling;}返回 ret;, 元素)
我实际上是在测试套件中使用此代码.
<div id="a">This is some
<div id="b">text</div>
</div>
Getting "This is some" is non-trivial. For instance, this returns "This is some text":
driver.find_element_by_id('a').text
How does one, in a general way, get the text of a specific element without including the text of it's children?
(I'm providing an answer below but will leave the question open in case someone can come up with a less hideous solution).
Here's a general solution:
def get_text_excluding_children(driver, element):
return driver.execute_script("""
return jQuery(arguments[0]).contents().filter(function() {
return this.nodeType == Node.TEXT_NODE;
}).text();
""", element)
The element passed to the function can be something obtained from the find_element...()
methods (i.e. it can be a WebElement
object).
Or if you don't have jQuery or don't want to use it you can replace the body of the function above above with this:
return self.driver.execute_script("""
var parent = arguments[0];
var child = parent.firstChild;
var ret = "";
while(child) {
if (child.nodeType === Node.TEXT_NODE)
ret += child.textContent;
child = child.nextSibling;
}
return ret;
""", element)
I'm actually using this code in a test suite.
这篇关于如何在 Selenium WebDriver 中获取元素的文本,而不包含子元素文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!