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

时间:2022-05-23 07:15:14

When I try to take some nonexistent content from page I catch this error:

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

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

How can I safely check exists this content or not? Here some examples that does not work:

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

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
}

THANKS, I helped myself with:

谢谢,我帮助自己:

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

3 个解决方案

#1


7  

Have you tried something like this?

你尝试过这样的事吗?

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

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

#2


7  

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

#3


0  

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

#1


7  

Have you tried something like this?

你尝试过这样的事吗?

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

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

#2


7  

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

#3


0  

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