如何安全地检查节点是否为空? (Symfony 2 Crawler)

时间:2012-08-07 13:18:46

标签: symfony web-crawler

当我尝试从页面中删除一些不存在的内容时,我会发现此错误:

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();
}

3 个答案:

答案 0 :(得分:12)

$marks = ($crawler->filter('.PropertyBody')->count()) ? $crawler->filter('.PropertyBody')->eq(2)->text() : '';

答案 1 :(得分:6)

你尝试过这样的事吗?

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

$this->assertContains('yourText', $text);

答案 2 :(得分:0)

try {
    $text = $crawler->filter('.PropertyBody')->eq(2)->text();
} catch (\InvalidArgumentException $e) {
    // Handle the current node list is empty..
}