首页 > 解决方案 > Selenium Python Behave 框架 - 如何单击 element_by _id

问题描述

我正在使用 Python 中的 Behave 框架,我以前没有使用过,我不确定如何单击 element_by_id。在发送登录密钥之前,我需要绕过一个 cookie 弹出窗口。

这是我的 .features 文件:

Feature: 
Login Functionality

Scenario: I can login

When visit url "https://example.com"

When I click on the button "accept-cookie-notification"

When field with name "user_email_login" is given "@gmail.com"

When field with name "user_password" is given "password"

Then title becomes "Dashboard"

这是我的 .py 文件:

脚步

@when('visit url "{url}"')
def step(context, url):
    context.browser.get(url)
    time.sleep(5)

@when('I click on the button "{selector}"')
def step(context, selector,):
    elem = context.driver.find_element_by_id("selector")
    elem.submit()
    time.sleep(5)

@when('field with name "{selector}" is given "{value}"')
def step(context, selector, value):
    elem = context.browser.find_element_by_id(selector)
    elem.send_keys(value)
    elem.submit()
    time.sleep(5)

@then('title becomes "{title}"')
def step(context, title):
    assert context.browser.title == title

稍后我还需要做 element_by_css 和 xpath 。

预先感谢您的任何帮助。

标签: seleniumselenium-webdriverpython-behave

解决方案


如果您使用 Behave,则使用 Selenium 非常简单。只需安装 behavior-webdriver 包https://pypi.org/project/behave-webdriver/它是一个步骤库,其中包含大量已定义的步骤以及 given-when-then 装饰器,例如:I click on the element "{element}" 并且您可以同时使用 id、css 和XPath 作为 {element} 参数。您不需要实现任何东西,只需在您的场景中使用预定义的步骤。这是我的代码示例:

Scenario: A user can log in.
Given the base url is "http://my_site:3000"
And I open the site "/#/login"
And the element "#email" is visible
When I add "my@email.com" to the inputfield "#email"
And I add "1234567" to the inputfield "#password"
And I click on the button "#loginButton"
Then I wait on element "//nav-toolbar//span[contains(text(),'Myself')]" to be visible
And I expect that the attribute "label" from element "#loggedUser" is "Finally, we made it!"

请不要忘记在您的 environment.py 方法 before_all() 和 after_all() 中添加处理 context.behave_drive,如上面的 HOWTO 页面中所述。


推荐阅读