从下拉菜单中查找元素

时间:2015-11-02 18:26:15

标签: perl selenium

这与Perl的CPAN的WWW :: Selenium模块有关。我在下面的HTML中遇到问题BigBroLot1446130409。这是一个下拉菜单。

这是HTML

<select name="lot_id" id="lot_id" title="">
<option value="">Select an Available Lot</option>


<option value="497">
  BigBroLot1446130409
  - 0g
  (100 credits to list)
</option>

<option value="500">
  BigBroLot1446133752
  - 199g
  (100 credits to list)
</option>

当我使用此代码时,它可以正常工作。

$locator = q{//select[@id="lot_id" and @name="lot_id"]};
$ret = $sel->wait_for_element_present($locator, $timeout);
$ret = $sel->select($locator, "value=497"); 

上面的代码有效,但在实际测试中,我需要找到基于文字BigBroLot1446130409而不是value=497的元素。

<option value="497">
  BigBroLot1446130409
  - 0g
  (100 credits to list)
</option>

这是一个下拉菜单,所以我想我需要使用文档中的以下功能:

$sel->select($select_locator, $option_locator)

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

如前所述,我想根据来自变量的&#39; BigBroLotXXXXXX&#39;名称从下拉菜单中进行选择。在模块的文档中有一个名为

的函数
$sel->get_select_options($select_locator)

Gets all option labels in the specified select drop-down.
$select_locator is an element locator identifying a drop-down menu
Returns an array of all option labels in the specified select drop-down. 

所以,我能够知道下拉菜单中的所有选择都在一个数组中。

从下拉菜单中选择元素的功能是:

$sel->select($select_locator, $option_locator)

此模块的文档声明$ option_locator可以是:

label=labelPattern:matches options based on their labels

label=regexp:^[Oo]ther

value=valuePattern:matches options based on their values.

id=id:matches options based on their ids.

index=index:matches an option based on its index (offset from zero).

首先,我需要定义我的选择数组所在的定位器,以便将其提供给get_select_options函数:

$locator = q{//select[@id="lot_id" and @name="lot_id"]};

my @array = $sel->get_select_options($locator);

对于笑话,我想验证@array确实有选择:

Select an Available Lot
BigBroLot1446130409 - 0g (100 credits to list)
BigBroLot1446087714 - 0g (100 credits to list)
BigBroLot1446665592 - 36g (100 credits to list)
BigBroLot1446060974 - 0g (100 credits to list)
BigBroLot1446668987 - 64g (100 credits to list)

$sel-select函数中所述,我可以使用索引查找元素,因此我在$sel->select模块的帮助下将其用作List::MoreUtils函数的option_locator。例如,让我们说$xyz = BigBroLot1446130409

use List::MoreUtils qw(first_index);
use 5.010;
my ($index) = grep { $array[$_] =~ /$xyz/ } (0 .. @array-1);

以下是从下拉菜单中选择我的元素的代码:

$locator = q{//select[@id="lot_id" and @name="lot_id"]};
$ret = $sel->select($locator,"index=$index");