【问题标题】:selenium's find element by xpath getting error where same expression in lxml is okselenium 通过 xpath 查找元素时出现错误,其中 lxml 中的相同表达式是可以的
【发布时间】:2015-02-03 19:14:45
【问题描述】:

我在各种 xpath 表达式中都遇到过这个问题。 selenium 的 find_element_by_xpath() 方法失败,而同一表达式的 lxml 给出了预期值。例如:

>>> lxml.html.fromstring(br.page_source).xpath('//a[@title="2"]/text()')
... ['\n\t\t\t\t\t\t2\n\t\t\t\t\t', '\n\t\t\t\t\t\t2\n\t\t\t\t\t']

>>> br.find_element_by_xpath('//a[@title="2"]/text()')
... InvalidSelectorException: Message: {"errorMessage":"The result of the xpath expression \"//a[@title=\"2\"]/text()\" is: [object Text]. It should be an element.","request":{"headers":{"Accept":"application/json","Accept-Encoding":"identity","Connection":"close","Content-Length":"108","Content-Type":"application/json;charset=UTF-8","Host":"127.0.0.1:47455","User-Agent":"Python-urllib/2.7"},"httpVersion":"1.1","method":"POST","post":"{\"using\": \"xpath\", \"sessionId\": \"85546b60-7c8e-11e4-b2ba-2bb5fbee7719\", \"value\": \"//a[@title=\\\"2\\\"]/text()\"}","url":"/element","urlParsed":{"anchor":"","query":"","file":"element","directory":"/","path":"/element","relative":"/element","port":"","host":"","password":"","user":"","userInfo":"","authority":"","protocol":"","source":"/element","queryKey":{},"chunks":["element"]},"urlOriginal":"/session/85546b60-7c8e-11e4-b2ba-2bb5fbee7719/element"}}
Screenshot: available via screen

为什么会发生这种情况,我该如何纠正?

【问题讨论】:

    标签: python selenium xpath selenium-webdriver lxml


    【解决方案1】:

    添加一些东西,如果结果不是一个元素,它在一个列表中。

        content = driver.find_element_by_id("aaa")
        all_children_by_xpath = content.find_elements_by_xpath("//p")
        for item in all_children_by_xpath:
            print item.text
    

    【讨论】:

      【解决方案2】:

      正如错误消息所述 - find_element_by_xpath() 中使用的 xpath 必须指向一个元素。在您的情况下,它指向一个文本节点

      如果要获取元素的文本,先找到元素再获取.text

      element = driver.find_element_by_xpath('//a[@title="2"]')
      print element.text
      

      【讨论】:

        猜你喜欢
        • 2019-10-21
        • 1970-01-01
        • 2020-08-08
        • 2016-03-12
        • 1970-01-01
        • 1970-01-01
        • 2016-10-31
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多