使用perl 5.22和Selenium :: Remote :: WebElement :: VERSION =' 0.2701'在OSX和Firefox上。第一次尝试使用Selenium(和XPath一样!)。
当我试图获得一个给定的"<选择>"孩子,然后列举其所有"<选项"> s因此:
use strict;
use warnings;
use Selenium::Remote::Driver;
use Selenium::Remote::WebElement;
use URI::file;
my $extraCaps = {"browser" => "Firefox", "browser_version" => "42.0","os" => "OSX","os_version" => "7","resolution" => "1024x768"};
my $driver = new Selenium::Remote::Driver('remote_server_addr' => 'localhost', 'port' => '4444','extra_capabilities' => $extraCaps);
$driver->get(URI::file->new_abs('./test.html')->as_string);
sleep(2);
# get <select> named 'SEL2':
my $sel2 = $driver->find_element('//select[@name="SEL2"]');
# this works, but it's not what i want: my $sel2_options = $driver->find_child_elements($sel2, '//select[@name="SEL2"]//option');
# get all the options for **that specific** <select>
my $sel2_options = $driver->find_child_elements($sel2, '//option');
foreach my $ap (@$sel2_options){
print "found option ".$ap->get_text()."\n";
}
sleep(1);
$driver->quit();
输入html文件(test.html)是:
<!DOCTYPE html>
<head></head>
<body>
<select name="SEL1" id="ID1">
<option value="SEL1-option11">SEL1-option1</option>
<option value="SEL1-option12">SEL1-option2</option>
<option value="SEL1-option13">SEL1-option3</option>
</select>
<select name="SEL2" id="ID2">
<option value="SEL2-option1">SEL2-option1</option>
<option value="SEL2-option2">SEL2-option2</option>
<option value="SEL2-option3">SEL2-option2</option>
</select>
</body></html>
我得到的输出是:
found option SEL1-option1
found option SEL1-option2
found option SEL1-option3
found option SEL2-option1
found option SEL2-option2
found option SEL2-option2
我不能仅列出SEL2的选项吗?
我做错了吗?在我看来,对于这种情况,find_child_elements忽略了它的第一个参数 - 据我所知 - WebElement将指定的选择器(//选项)应用于它。
另一方面,这可以按预期工作,但它以某种方式违背了目的:
my $sel2_options = $driver->find_child_elements($sel2, '//select[@name="SEL2"]//option');
非常感谢,
bliako
答案 0 :(得分:1)
/
始终引用文档的根节点。这就是为什么您只从option
获取所有option
个元素而不是$sel2
个元素的原因。尝试在XPath的开头添加.
以使其相对于当前元素上下文:
my $sel2_options = $driver->find_child_elements($sel2, './/option');