LoginSignup
135
133

More than 5 years have passed since last update.

Goutteでスクレイピングする方法めも

Last updated at Posted at 2014-05-23

単にスクレイピングするだけならSymfony2の機能テストと基本的に同じ

直接URLにアクセスする

$client = new \Goutte\Client();

// GET
$client->request('GET', 'http://example.com/some/url');

// POST
$client->request('POST', 'http://exmaple.com/some/post/url', ['foo' => 'bar'], ['image' => '/var/www/myimage.jpg']);

アクセス先の特定のタグの内容・属性を取得する


$client = new \Goutte\Client();

// $crawlerは\Symfony\Component\DomCrawler\Crawler
$crawler = $client->request('GET', 'http://example.com/some/url');

// <h1>this is header!</h1>タグの内容
$crawler->filter('h1')->text(); // →this is header!

// <h2><a href="./subpage.html">サブタイトル</a></h2>タグのhref属性
$crawler->filter('h2 a')->attr('href'); // →./subpage.html

// <ul><li>test1</li><li>test2</li></ul> 全部のliタグの内容
$lists = $crawler->filter('ul li')->each(function(Crawler $node){
    return $node->text();
});
// → $listsは['test1', 'test2']

// 取得したHTML全体
$crawler->html();

アクセス先にあるリンクをクリックする

$client = new \Goutte\Client();

// まずリンクのあるURLにアクセス
$crawler = $client->request('GET', 'http://example.com/some/url');

// 「ここをクリック」をクリックしてリンク先に遷移
$client->click($crawler->selectLink('ここをクリック')->link());

アクセス先にあるフォームを送信する

$client = new \Goutte\Client();

// まずフォームのあるURLにアクセス
$crawler = $client->request('GET', 'http://example.com/some/form');

// 「ログイン」というボタンクリックで送信されるフォームを選択
$form = $crawler->selectButton('ログイン')->form();
$form['username'] = 'testuser';
$form['password'] = 'mypassword';
$crawler->submit($form);

URLにアクセスしてステータスコードを調べる

$client = new \Goutte\Client();

$client->request('GET', 'http://example.com/good/url');
$client->getResponse()->getStatus(); // →200

$client->request('GET', 'http://example.com/bad/url');
$client->getResponse()->getStatus(); // →404

// $client->getResponse()は\Symfony\Component\BrowserKit\Response

アクセス時に使うUserAgentを設定する

$client = new \Goutte\Client();

// UserAgentを"MyCrawler 1.0"に設定
$client->setHeader('User-Agent', 'MyCrawler 1.0');

$client->request('GET', '...'); // MyCrawler 1.0としてアクセス
$client->request('POST', '...'); // MyCrawler 1.0としてアクセス

// 以後、再度setHeader('User-Agent')で何か違うUAを設定するまでずっとこのまま
135
133
2

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
135
133