Selenium Python Behave 框架 - 如何点击 element_by _id

Selenium Python Behave framework - How do I click on an 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。

提前感谢您的帮助。

你需要的是阅读一些文档,试着看看像 taht 这样你有最常用命令的东西 http://allselenium.info/python-selenium-commands-cheat-sheet-frequently-used/

如果您使用 Behave,使用 Selenium 将非常简单。只需安装 behave-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 页面所述。