我正在研究硒包装器。我想检查网页上的元素是否可见。该函数获取selector
遵循模式的输入变量,"selector=value"
例如"id=content"
,但也可能是 this "link_text=Hello World"
。搜索函数将该字符串分成两部分以搜索实际元素并将其返回以用于错误处理。异常消息应同时说明选择器和值:
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
我可以将分离过程移动到它自己的函数中,然后在异常和搜索函数中调用它,但我真的不想这样做,因为这意味着我要执行相同的代码两次。