首页 > 解决方案 > 如何使用 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;在脚本中并不会抑制它。

我怎样才能压制这个“警告”?

标签: seleniumperlwarningssuppress-warningsselenium-remotedriver

解决方案


使用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 一起使用。


推荐阅读