【问题标题】:How can I safely check is node empty or not? (Symfony 2 Crawler)如何安全地检查节点是否为空? (Symfony 2 爬虫)
【发布时间】:2012-08-07 13:18:46
【问题描述】:

当我尝试从页面中获取一些不存在的内容时,我发现了这个错误:

The current node list is empty.
500 Internal Server Error - InvalidArgumentException 

如何安全地检查此内容是否存在?这里有一些不起作用的例子:

if($crawler->filter('.PropertyBody')->eq(2)->text()){
    // bla bla
}

if(!empty($crawler->filter('.PropertyBody')->eq(2)->text())){
    // bla bla
}
if(($crawler->filter('.PropertyBody')->eq(2)->text()) != null){
    // bla bla
}

谢谢,我帮自己解决了:

$count = $crawler->filter('.PropertyBody')->count();
if($count > 2){
    $marks = $crawler->filter('.PropertyBody')->eq(2)->text();
}

【问题讨论】:

  • 谢谢伙计。您的解决方案为我节省了很多!
  • 检查计数有帮助!

标签: symfony web-crawler


【解决方案1】:
$marks = $crawler->filter('.PropertyBody')->count()
    ? $crawler->filter('.PropertyBody')->eq(2)->text() 
    : '';

【讨论】:

    【解决方案2】:

    你尝试过这样的事情吗?

    $text = null;
    if (!empty($body = $crawler->filter('.PropertyBody'))) {
        if (!empty($node = $body->eq(2))) {
            $text = $node->text();
        }
    }
    
    $this->assertContains('yourText', $text);
    

    【讨论】:

    • 空函数还是被绕过了。
    • 对我也不起作用。但是使用 ->count() 就可以了
    【解决方案3】:
    try {
        $text = $crawler->filter('.PropertyBody')->eq(2)->text();
    } catch (\InvalidArgumentException $e) {
        // Handle the current node list is empty..
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-06-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-29
      相关资源
      最近更新 更多