selenium - 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 。
预先感谢您的任何帮助。
解决方案
如果您使用 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 页面中所述。
推荐阅读
- java - 对于小型数据集,收集比第一次花费更多时间
- ios - 如何在我的颤振应用中添加连续移动的背景?
- java - 使用 @SqsListener 注解为 FIFO 配置消息组 ID
- javascript - 使用 Sequlize 获取“TypeError:无法读取未定义的属性 'findAll'”
- ios - 如何在iOS中动态地在UIView中制作不同的圆角值?
- swift - T swift 数组的替代方案
- javascript - React-Native Animated.spring 回调正在延迟
- ruby-on-rails - 如何注销使用自定义设计策略登录的用户
- r - 什么解释了 R 中 x.x5 的小数点后 1 位舍入?
- php - 获取一个月的最后一天