首页 > 解决方案 > 剧作家蟒蛇。- 如何检查元素是否隐藏

问题描述

我目前正在使用 Playwright / Python / Pytest,我正在尝试以特定类型的用户角色身份登录,然后检查各种按钮是否可见或隐藏。

我正在使用页面对象并为每个按钮元素设置属性,即

    @property
    def manage_placements_button(self):
    return self.page.wait_for_selector("xpath=//h3[normalize-space()='Manage Placements']")
    
    @property
    def my_holiday_button(self):
    return self.page.wait_for_selector("xpath=//h3[normalize-space()='My Holiday']")

    @property
    def my_payments_button(self):
    return self.page.wait_for_selector("xpath=//h3[normalize-space()='My Payments']")

    @property
    def my_compliances_button(self):
    return self.page.wait_for_selector("xpath=//h3[normalize-space()='My Compliances']")

然后我对可见按钮使用验证方法:

    def verify_candidiate_can_see(self):
    result = self.manage_timesheets_button.is_visible()
    result = self.my_payments_button.is_visible() and result
    result = self.my_holiday_button.is_visible() and result
    result = self.my_compliances_button.is_visible() and result
    return result

这工作正常,它为测试中的断言传回 true。

然后,我尝试使用以下方法对隐藏值执行相同操作:

    def verify_candidiate_cant_see(self):
    result = self.manage_placements_button.is_hidden()
    return result

但我收到此错误 - 等待选择器 "xpath=//h3[normalize-space()='Manage Placements']" 可见

这是测试:

  @pytest.mark.order(2)
  def test_candidate_login(context, env):
  page = context.new_page()
  home_page = HomePage(page)
  login_page = LoginPage(page)
  login_page.navigate(env)
  login_page.login(env, "Candidate")
  result1 = home_page.verify_candidiate_can_see()
  assert result1 == True
  result2 = home_page.verify_candidiate_cant_see()
  assert result2 == True
  context.close()

我假设当我添加 is_hidden 时它会没问题,因为页面上不存在该元素,但它似乎仍在等待它可见。任何帮助将不胜感激

标签: automated-testspytestwebautomationplaywrightplaywright-python

解决方案


您可以等待选择器被隐藏:

return self.page.wait_for_selector("xpath=something", state="hidden")

当元素不存在时返回,如果它在页面上,它会等到它隐藏。

请参阅此处以供参考。


推荐阅读