【问题标题】:How to suppress "warning" using Selenium::Remote::Driver?如何使用 Selenium::Remote::Driver 抑制“警告”?
【发布时间】:2023-03-09 18:12:01
【问题描述】:
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[.="未找到文本"]

根据docs,如果没有找到元素,该函数会发出“警告”,但在脚本中包含no warnings; 不会抑制它。

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

【问题讨论】:

    标签: selenium perl warnings suppress-warnings selenium-remotedriver


    【解决方案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::Driver 一起使用。

    【讨论】:

    • find_element_by_xpath 发出警告。 find_element 会发牢骚。
    【解决方案2】:

    根据docs,如果没有找到元素,该函数会发出“警告”,但在脚本中包含no warnings; 不会抑制它。

    没错。 warnings 杂注是词法的。在您的代码中添加no warnings 只会影响您的代码。它不会关闭您的代码使用的其他模块中的警告。正如the documentation 所说:

    这个 pragma 就像“strict” pragma 一样工作。这意味着警告 pragma 的范围仅限于封闭块。这也意味着 pragma 设置不会跨文件泄漏(通过“use”、“require”或“do”)。这允许作者独立定义将应用于其模块的警告检查程度。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-02-08
      • 1970-01-01
      • 1970-01-01
      • 2018-07-11
      • 2019-02-25
      • 2011-03-18
      • 1970-01-01
      相关资源
      最近更新 更多