はじめに
こんにちは、エンジニアのkeitaMaxです。
今回はRoach PHPを使用していた時にThe current node list is empty.
というエラーが出た時の話をします。
エラー内容について
スクレイピングを実行した時に以下のエラーが出ました。
The current node list is empty.
実際のコードは以下のような感じです。
$subtitle = $response
->filter('main> div:nth-child(2) p:first-of-type')
->text();
サンプルと同じですが、指定しているURLを修正したので、'main> div:nth-child(2) p:first-of-type'
ここでしている要素では ->text()
がとれずにエラーになってしまっているようです。
解決策
解決策は簡単で、エラーが出ている箇所が以下のようにInvalidArgumentExceptionをthrowしているため、エラーをキャッチしてあげれば解決します。
throw new \InvalidArgumentException('The current node list is empty.');
具体的には以下のようにします。
try{
$title = $response
->filterXPath('descendant-or-self::main/div[2]//p[1]')
->text();
yield $this->item([
'title' => $title ?? '',
]);
}catch(InvalidArgumentException $e){
echo($e);
}
おわりに
この記事での質問や、間違っている、もっといい方法があるといったご意見などありましたらご指摘していただけると幸いです。
最後まで読んでいただきありがとうございました!