Selenium:如何从选择菜单中选择一个选项?

2022-01-25 00:00:00 selenium selenium-rc php phpunit

我正在使用 PHPUnit Selenium 扩展在 PHP 中编写 Selenium 测试.

I am writing a Selenium test in PHP using the PHPUnit Selenium extension.

我知道如何在文本字段中输入内容:

I know how to type something into a text field:

$this->type('fieldName', 'value');

但是如何从下拉菜单中选择一个选项?

But how do I select an option from a drop-down menu?

推荐答案

要扩展其他(准确)答案,您可以根据选项的标签、值、id 或索引进行选择.来自 http://release.seleniumhq.org/selenium-core 的官方参考资料/1.0/reference.html:

To expand on the other (accurate) answers, you can select based on the label, value, id, or index of the options. From the official reference available at http://release.seleniumhq.org/selenium-core/1.0/reference.html:

select(selectLocator, optionLocator)

参数:

  • selectLocator - 标识下拉菜单的元素定位器
  • optionLocator - 选项定位器(默认为标签)

使用选项定位器从下拉列表中选择一个选项.

Select an option from a drop-down using an option locator.

选项定位器提供了指定 HTML Select 元素选项的不同方式(例如,用于选择特定选项,或用于断言所选选项满足规范).选择选项定位器有多种形式.

Option locators provide different ways of specifying options of an HTML Select element (e.g. for selecting a specific option, or for asserting that the selected option satisfies a specification). There are several forms of Select Option Locator.

  • label=labelPattern:根据标签(即可见文本)匹配选项.(这是默认设置.)
    • label=regexp:^[Oo]其他
    • label=labelPattern: matches options based on their labels, i.e. the visible text. (This is the default.)
      • label=regexp:^[Oo]ther
      • 值=其他
      • id=option1
      • 索引=2

      如果没有提供选项定位器前缀,则默认行为是匹配标签.

      If no option locator prefix is provided, the default behaviour is to match on label.

相关文章