使用Python和Selenium,我想做如下操作:
myList = elementList[0].find_elements_by_xpath("/some/xpath")
textValue = myList[0].find_elements_by_xpath("text()[1]")
(最后,两个步骤都将嵌套在for循环中)
但第二行崩溃了:
Expected an element or WindowProxy, got: [object Text] {}
最明显的建议是使用Selenium的内置函数.text
(如myList[0].text
),但在我的例子中这是不合适的,因为myList
中的第一个(但只有那个)元素有两个文本值,并且.text
将它们连接成一个字符串。你知道吗
那么如何在myList
中的元素上“应用”XPath函数text()[1]
,以获得该元素的文本值呢?你知道吗
更新:我有个主意。如果我在问题的第一行代码中添加text()
,它就可以工作了。我将其解释为text()
需要位于正确XPath的末尾?我说得对吗?你知道吗
在我的第二行中使用一些通用的通配符XPath是不可能的,因为那里只有一个元素,而且不存在歧义的风险?比如textValue = myList[0].find_elements_by_xpath("*/text()[1]")
?你知道吗
myList[0].find_elements_by_xpath("text()[1]")
将返回一个WebElement数组(如果有的话),而不是一个文本字符串。你试过以下两种方法吗?我认为他们应该工作。。。你知道吗或者
如果你能试一下,让我知道,看看效果如何。你知道吗
好的,最后我用python编写了两个方法。一个仅获取父文本内容(不包括子文本),另一个基于文本节点位置获取内容。你知道吗
注意:如果要在其他语言中使用这些方法,请确保根据您的语言更新
driver.execute_script
和'strip()`。(使用strip()修剪返回值)。你知道吗方法1:获取\u文本\u排除\u子元素(element)
#参数-元素
#return-仅元素文本(不包括子文本)
方法2:通过位置(元素,textposition)从父级获取文本
#参数-元素
#参数-textposition(从1开始,指定要返回的文本节点的索引)
#return—在位置处指定的父文本
如何使用这些方法
相关问题 更多 >
编程相关推荐