11
13

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Goutte -PHPスクレイピングライブラリ

11
Posted at

Symfony2の機能を利用した「Goutte」というWebスクレイピングライブラリがある。
https://github.com/fabpot/Goutte
Githubからダウンロードし、中の「goutte.phar」ファイルのみをサーバーに配置し、
読みこむだけで利用できる。

require_once 'goutte.phar';
$client = new Client();
$crawler = $client->request('GET', 'http://example.com');
echo $crawler->filter('#contents')->text();  //id="contents"内の文字列が出力される

HTMLのパースにはSymfonyのDomCrawlerコンポーネントを利用していて、
上記のようにCSSセレクタを用いて取得することができる。
Crawlerクラスのソースコードは以下で確認できる。

しばらくGoutteを使ってみたが、requestメソッドのHTMLパース時に
マルチバイト文字の扱いで次のようなエラーが発生した。

Error parsing body - doesn't seem to be a chunked message

最初は単純にphp-mbstringをインストールしてやることで解決したのだけど、
別のHTMLをパースする際にまた同様のエラーが発生してしまい、今度は原因がわからなかったので、
現在は結局Simple HTML DOM Parserなどと併用する形で使っている。

11
13
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
11
13

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?