How can I safely check is node empty or not? (Symfony 2 Crawler)

冷暖自知 提交于 2019-12-20 11:18:52

问题


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

回答1:


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:


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



回答3:


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


来源:https://stackoverflow.com/questions/11846918/how-can-i-safely-check-is-node-empty-or-not-symfony-2-crawler

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!