Python 和 Selenium - 使用 XPath text() 而不是 myElement.text?

2024-09-27 07:27:07 发布

您现在位置:Python中文网/ 问答频道 /正文

使用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]")?你知道吗


Tags: 函数text文本元素byselenium步骤some
2条回答

myList[0].find_elements_by_xpath("text()[1]")将返回一个WebElement数组(如果有的话),而不是一个文本字符串。你试过以下两种方法吗?我认为他们应该工作。。。你知道吗

myList[0].get_attribute(‘text’)

或者

myList[0].get_attribute(‘innerHTML’)

如果你能试一下,让我知道,看看效果如何。你知道吗

好的,最后我用python编写了两个方法。一个仅获取父文本内容(不包括子文本),另一个基于文本节点位置获取内容。你知道吗

注意:如果要在其他语言中使用这些方法,请确保根据您的语言更新driver.execute_script和'strip()`。(使用strip()修剪返回值)。你知道吗

方法1:获取\u文本\u排除\u子元素(element)

#参数-元素

#return-仅元素文本(不包括子文本)

def get_text_exclude_children(element):
    return driver.execute_script(
        """
        var parent = arguments[0];
        var child = parent.firstChild;
        var textValue = "";
        while(child) {
            if (child.nodeType === Node.TEXT_NODE)
                textValue += child.textContent;
                child = child.nextSibling;
        }
        return textValue;""",
        element).strip()

方法2:通过位置(元素,textposition)从父级获取文本

#参数-元素

#参数-textposition(从1开始,指定要返回的文本节点的索引)

#return—在位置处指定的父文本

def get_text_from_parent_by_position(element,textPosition=1):
    return driver.execute_script(
        """ var parent = arguments[0];
            var textPosition = arguments[1];
            var txtPosition = 0;
            var child = parent.firstChild;
            var textValue="";
            while(child) {
              if (child.nodeType === 3){                        
                if (txtPosition===(textPosition-1)){
                  textValue = child.textContent;                
                  break;
                }}else{txtPosition+=1;}
              child = child.nextSibling;
            }
        return textValue;""",
        element,textPosition).strip()

如何使用这些方法

myList = elementList[0].find_elements_by_xpath("/some/xpath")
listElement = myList[0]
onlyParentText = get_text_exclude_children(listElement)
onlyFirstTextNode = get_text_from_parent_by_position(listElement,1)
print("only parent text: " + onlyParentText)
print("First TextNode text: " + onlyFirstTextNode)

相关问题 更多 >

    热门问题