我正在制作一个硒脚本,用于搜索任何可见元素,打印它们是否显示,然后将它们附加到列表(ButtonDisplayed 或 ButtonNotDisplayed)。然而,这是非常重复的,因为我必须为我检查的每个元素创建一个 if else 语句。有没有办法让我缩短这段代码?
if login.is_displayed():
logInButtonDisplayed = "Login is displayed"
print(logInButtonDisplayed)
buttonDisplayed.append(logInButtonDisplayed)
else:
logInButtonNotDisplayed = "Login is not displayed"
print(logInButtonNotDisplayed)
buttonNotDisplayed.append(logInButtonNotDisplayed)
if login.is_enabled():
logInButtonEnabled = "Log In button is enabled"
print(logInButtonEnabled)
buttonEnabled.append(logInButtonEnabled)
else:
logInButtonDisabled = "Log In button is disabled"
print(logInButtonDisabled)
buttonDisabled.append(logInButtonDisabled)
您可以尝试使用 f 字符串和条件表达式。
def check_element_status(element, displayed_list, not_displayed_list, enabled_list, disabled_list):
display_status = "displayed" if element.is_displayed() else "not displayed"
enabled_status = "enabled" if element.is_enabled() else "disabled"
display_message = f"{element.get_attribute('id')} is {'' if element.is_displayed() else 'not '}displayed"
enabled_message = f"{element.get_attribute('id')} is {'' if element.is_enabled() else 'not '}enabled"
print(display_message)
print(enabled_message)
displayed_list.append(display_message)
not_displayed_list.append(display_message) if not element.is_displayed() else None
enabled_list.append(enabled_message)
disabled_list.append(enabled_message) if not element.is_enabled() else None
# Assuming you have login element
check_element_status(login, buttonDisplayed, buttonNotDisplayed, buttonEnabled, buttonDisabled)