26

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

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

3 回答 3

23
$marks = $crawler->filter('.PropertyBody')->count()
    ? $crawler->filter('.PropertyBody')->eq(2)->text() 
    : '';
于 2016-11-13T17:59:59.707 回答
7

你有没有尝试过这样的事情?

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

$this->assertContains('yourText', $text);
于 2012-08-07T13:21:31.657 回答
1
try {
    $text = $crawler->filter('.PropertyBody')->eq(2)->text();
} catch (\InvalidArgumentException $e) {
    // Handle the current node list is empty..
}
于 2016-11-25T11:16:17.850 回答