LoginSignup
1
2

More than 5 years have passed since last update.

PHP スクレイピングライブラリ Goutte で text() が空のときエラーじゃなくて空文字が返るようにする

Last updated at Posted at 2017-11-05

経緯

webスクレイパとしてGoutteを使っています。
https://github.com/FriendsOfPHP/Goutte

下の記事にありますが、
https://qiita.com/zaburo/items/45d748ae3966bf08323f

対象のタグが無いときか、空文字のときに、
エラーを吐いて動かなくなるので、
いっそエラーを吐かなくしました。

コード

Crawler.phpの大体551行目くらいで一行書き換えるだけです。

before.php
    public function text()
    {
        if (!count($this)) {
            throw new \InvalidArgumentException('The current node list is empty.');
        }

        return $this->getNode(0)->nodeValue;
    }
after.php
    public function text()
    {
        if (!count($this)) {
            //throw new \InvalidArgumentException('The current node list is empty.');
            return '';
        }

        return $this->getNode(0)->nodeValue;
    }

注意

この変更によって、タグの中が空文字なのかタグ自体がないのかが判定できなくなるかもしれません。後日ちゃんとコード追います。
引用の記事にgoutte自体を書き換えないで空文字を出力するやり方があるので、そちらのほうがいいかもしれません。
今回の自分の場合タグが空でも空文字でも同じで問題なかったのでこうしました。

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2