提问人:CJ7 提问时间:7/16/2020 更新时间:7/16/2020 访问量:536
如何使用 Selenium::Remote::D river 抑制“警告”?
How to suppress "warning" using Selenium::Remote::Driver?
问:
no warnings;
use Selenium::Remote::Driver;
my $driver = Selenium::Remote::Driver->new;
$driver->get('https://www.crawler-test.com/');
$driver->find_element_by_xpath('//a[.="text not found"]');
我怎样才能得到上面的代码不打印这个警告:
执行命令时出错:没有这样的元素:无法定位 元素://a[.=“找不到文本”]
根据文档,如果未找到元素,该函数会发出“警告”,但在脚本中不会抑制它。no warnings;
如何抑制此“警告”?
答:
4赞
ikegami
7/16/2020
#1
使用代替 .前者会引发异常,而不是发出警告。您可以使用以下包装器捕获这些异常:find_element
find_element_by_xpath
sub nf_find_element {
my $node;
if (!eval {
$node = $web_driver->find_element(@_);
return 1; # No exception.
}) {
return undef if $@ =~ /Unable to locate element|An element could not be located on the page using the given search parameters/;
die($@);
}
return $node;
}
sub nf_find_elements {
my $nodes;
if (!eval {
$nodes = $web_driver->find_elements(@_);
return 1; # No exception.
}) {
return undef if $@ =~ /Unable to locate element|An element could not be located on the page using the given search parameters/;
die($@);
}
return wantarray ? @$nodes : $nodes;
}
sub nf_find_child_element {
my $node;
if (!eval {
$node = $web_driver->find_child_element(@_);
return 1; # No exception.
}) {
return undef if $@ =~ /Unable to locate element|An element could not be located on the page using the given search parameters/;
die($@);
}
return $node;
}
sub nf_find_child_elements {
my $nodes;
if (!eval {
$nodes = $web_driver->find_child_elements(@_);
return 1; # No exception.
}) {
return undef if $@ =~ /Unable to locate element|An element could not be located on the page using the given search parameters/;
die($@);
}
return wantarray ? @$nodes : $nodes;
}
nf
代表“非致命”。
为 Selenium::Chrome 编写,但也应该与 Selenium::Remote::D river 一起使用。
评论
0赞
CJ7
7/16/2020
find_element_by_xpath
发出警告。 会呱呱叫。find_element
3赞
Dave Cross
7/16/2020
#2
根据文档,如果未找到元素,该函数会发出“警告”,但在脚本中不会抑制它。
no warnings;
没错。编译指示是词汇的。添加到代码中只会影响代码。它不会关闭代码使用的其他模块中的警告。正如文档所说:warnings
no warnings
此编译指示的工作方式与“严格”编译指示类似。这意味着警告编译指示的范围仅限于封闭块。这也意味着编译指示设置不会跨文件泄漏(通过“use”、“require”或“do”)。这允许作者独立定义将应用于其模块的警告检查程度。
评论