我正在开发一个selenium包装器。我想检查网页上的元素是否可见。函数得到输入变量selector
,它遵循模式"selector=value"
,例如"id=content"
,但也可以是这个"link_text=Hello World"
。search函数将该字符串分成两个部分,用于搜索实际元素,并返回该字符串以用于错误处理。异常消息应该同时声明选择器和值:
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