Selenium Python表现为WebDriverWait

时间:2018-08-10 10:04:06

标签: python selenium-webdriver python-behave

我正在尝试使用WebDriverWait使页面等待,直到它从登录页面转到用户面板页面。

from features.browser import Browser
from features.locators import LoginPageLocators
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

class LoginForm(Browser):
    def log_in_as(self, username, password):
        username_field = self.driver.find_element(*LoginPageLocators.EMAIL_FIELD)
        password_field = self.driver.find_element(*LoginPageLocators.PASSWORD_FIELD)
        username_field.send_keys(username)
        password_field.send_keys(password)
        submit_btn = self.driver.find_element(*LoginPageLocators.LOGIN_BTN)
        submit_btn.click()

        try:
            element = WebDriverWait(self, 10).until(EC.presence_of_element_located((By.XPATH, '//*[@id="ssr-webnav"]/div/div[1]/nav[2]/div[2]')))
        finally:
            print("Log In Succesfull")

然后我逐步命名为

@step(u'I log in as registered user')
def step_impl(context):
    context.login_form.log_in_as("example@gmail.com", "password123")

在environment.py中,我通过

进行链接
def before_all(context):
    context.browser = Browser()
    context.login_form = LoginForm()

登录按预期进行,但是当我添加WebdriverWait时会引发错误:

Traceback (most recent call last):
  File "\behave\model.py", line 1329, in run
    match.run(runner.context)
  File "\behave\matchers.py", line 98, in run
    self.func(context, *args, **kwargs)
  File "features\steps\steps.py", line 13, in step_impl
    context.login_form.log_in_as("example@gmail.com", "password123")
  File "\features\pages\login.py", line 27, in log_in_as
    EC.presence_of_element_located((By.XPATH, '//*[@id="ssr-webnav"]/div/div[1]/nav[2]/div[2]')))
  File "\webdriver\support\wait.py", line 71, in until
    value = method(self._driver)
  File "\webdriver\support\expected_conditions.py", line 63, in __call__
    return _find_element(driver, self.locator)
  File \webdriver\support\expected_conditions.py", line 397, in 
    _find_element
    return driver.find_element(*by)
  AttributeError: 'LoginForm' object has no attribute 'find_element'

任何想法我想念什么? 谢谢

1 个答案:

答案 0 :(得分:2)

通过查看Python的Selenium documentation,看来您需要将webdriver对象传递给WebDriverWait(...)。您将self而不是self.driver传递到函数调用中。

所以这个

                        vvvv
element = WebDriverWait(self, 10).until(EC.presence_of_element_located((By.XPATH, '//*[@id="ssr-webnav"]/div/div[1]/nav[2]/div[2]')))

需要是这个

element = WebDriverWait(self.driver, 10).until(EC.presence_of_element_located((By.XPATH, '//*[@id="ssr-webnav"]/div/div[1]/nav[2]/div[2]')))