获取祖先Web元素属性时出错

时间:2018-06-18 20:50:39

标签: c# python selenium-webdriver xpath

我有一个方法来获取web_element的祖先元素:

def find_ancestor(self, name):
    element = self.driver.find_element_by_name(name)
    ancestor = element.find_element_by_xpath("ancestor::*")
    print(ancestor)
    attr = ancestor.get_attribute("outerHTML")
    print(attr)

print(ancestor)的输出为<selenium.webdriver.remote.webelement.WebElement (session="43f99228044a37dab999a9512b5e268e", element="0.22129539497775563-3")> 当我尝试访问和打印属性时,出现错误:UnicodeEncodeError: 'charmap' codec can't encode character u'\xae' in position 292: character maps to <undefined> 我的脚本顶部有# -*- coding: utf-8 -*我错过了什么/做错了什么?我的感觉是&#39;祖先&#39;返回与其他xpath轴不同!?

背景/奖金帮助 理想情况下,我希望方法能够获得父级,前级兄弟,后级兄弟等。 但是当我在表格上尝试这样的操作时,preceding-sibling没有得到前一个单元格(没有找到任何元素),而parent我得到的是同一个元素(相同的表格单元而不是表格行) )。 我正在展示python但不记得c#中的答案。

1 个答案:

答案 0 :(得分:0)

我将最后一行更改为print(attr.encode("utf-8")) 哪个有效。当我在脚本的顶部# -*- coding: utf-8 -*时,我不明白为什么需要这样做。但我现在看到的是祖先。