Python 3.8 海象运算符与 not 和分配多个变量

Python 3.8 Walrus Operator with not and assigning mutliple variables

我正在研究硒包装器。我想检查网页上的元素是否可见。该函数获取输入变量 selector,它遵循模式 "selector=value",例如 "id=content",但也可能是 "link_text=Hello World"。搜索函数将该字符串分成两部分,用于搜索实际元素和 returns 用于错误处理。例外消息应说明选择器和值:

class KeywordFailed(Exception):
    
    def __init__(self, message):
        self.message = message
        super().__init__(self.message)

class ElementFoundButNotVisible(KeywordFailed):
    def __init__(self, element, selector):
        super().__init__("element: \"" + element + "\" with selector: \"" + selector + "\" is not visible")

class DefaultKeywords:

    browser = webdriver.Firefox()

    def selectElement(self, selector):
        selectorValue = selector.split("=")[1]
        selector = selector.split("=")[0]
        try:
            if selector == "id":
                element = self.browser.find_element_by_id(selectorValue)
            elif selector == "xpath":
                element = self.browser.find_element_by_xpath(selectorValue)
            elif selector == "link_text":
                element = self.browser.find_element_by_link_text(selectorValue)
            elif selector == "partial_link_text":
                element = self.browser.find_element_by_partial_link_text(selectorValue)
            elif selector == "name":
                element = self.browser.find_element_by_name(selectorValue)
            elif selector == "class_name":
                element = self.browser.find_element_by_class_name(selectorValue)
            elif selector == "css_selector":
                element = self.browser.find_element_by_css_selector(selectorValue)
            elif selector == "tag":
                element = self.browser.find_element_by_tag_name(selectorValue)
        except NoSuchElementException:
            raise ElementNotFound(selectorValue, selector)
        else:
            return element, selector

    def findAndCheckIfVisible(self, selector):
        if (value, selector) := not self.selectElement(selector).is_displayed():
            raise ElementFoundButNotVisible(element, selector)
...

执行时出现以下错误:

SyntaxError: cannot use assignment expressions with tuple

我可以将分离过程移动到它自己的一个函数中,并在异常和搜索函数中调用它,但我真的不想这样做,因为那意味着我正在执行相同的代码两次。

您不能使用赋值表达式的解包形式。相反,考虑使用赋值表达式为返回的元组创建一个名称,然后从表达式的名称中解包:

def findAndCheckIfVisible(self, selector):
   if not (result:=self.selectElement(selector).is_displayed()):
      raise ElementFoundButNotVisible(element, selector)
   value, selector = result

此外,考虑使用 getattr:

,而不是针对每种选择器类型的显式条件
try:
   element = getattr(self.browser, f'find_element_by_{selector}')(selectorValue)
except NoSuchElementException:
   pass