selenium - 如何使用 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[.="text not found"]
根据文档,如果没有找到元素,该函数会发出“警告”,但no warnings;
在脚本中并不会抑制它。
我怎样才能压制这个“警告”?
解决方案
使用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::Driver 一起使用。
推荐阅读
- mysql - 为什么每次尝试上传数据库时mysql都会给我错误1136?
- java - 如何使用 Java 进行简单的密码登录
- python - 使用 pandas 将 csv 转换为 json 以在 highcharts highstock 图中绘制两个系列而不是一个系列
- c# - UWP 通知中是否可以有特定的斜体或粗体文本?
- javascript - React-native:未定义不是对象(评估'_this3.props.navigation.navigate')
- reactjs - 可以与自定义 Javascript 对象处理程序进行交互
- c - 灵活的数组成员和指针成员:利弊?
- python - 将生成的 JSON 保存到 SQLite - Django
- solidity - 在 Solidity 中,为什么使用 'is' 关键字,而不是 'extends' 进行继承
- ruby-on-rails - rails 5.0.7 多个默认 gem,无法卸载任何默认 gem