selenium的find元素由xpath获取错误,其中lxml中的相同表达式正常

时间:2014-12-05 15:10:48

标签: python selenium xpath selenium-webdriver lxml

我遇到过各种xpath表达式的问题。 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

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

2 个答案:

答案 0 :(得分:2)

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

如果您想获取元素的文字,请先找到该元素,然后获取.text

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

答案 1 :(得分:0)

只需添加一些内容,如果结果不是一个元素,则它在列表中。

    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