goutte.pharというライブラリを使いスクレイピングを考えています。
goutte.pharを使うと、下記のように書くだけで
http://www.example.com/form.php のボタンBtn1を押し、そこで表示された中から、<table name="small">にあるtdの各々のテキストを順番に全て取得可能です。
<?php require_once 'goutte.phar'; $client = new \Goutte\Client(); // まずフォームのあるURLにアクセス $crawler = $client->request('GET', 'http://www.example.com/form.php''); // 「Btn1」というボタンクリックで送信されるフォームを選択 $form = $crawler->selectButton('Btn1')->form(); $crawler = $client->submit($form, array()); $crawler->filter("table.small td")->each(function ($node){ echo $node->text(); // プレーンテキストを取得 }); ?>【取得結果】
105-0004 東京都港区新橋1-2-3
105-0004 東京都港区新橋2-3-4
105-0004 東京都港区新橋4-5-6
105-0006 東京都港区芝1-23-3
105-0007 東京都港区芝5-20-1
また、下記のようにすると<table name="small">にあるaタグのついたテキストとURLの取得が可能です。
<?php require_once 'goutte.phar'; $client = new \Goutte\Client(); // まずフォームのあるURLにアクセス $crawler = $client->request('GET', 'http://www.example.com/form.php''); // 「Btn1」というボタンクリックで送信されるフォームを選択 $form = $crawler->selectButton('Btn1')->form(); $crawler = $client->submit($form, array()); $crawler->filter("table.small a")->each(function ($node){ echo $node->attr('href'); // attr->('attribute') //URL取得 }); ?>【取得結果】
http://www.example.com/page1234.html
http://www.example.com/page1236.html
http://www.example.com/page1366.html
http://www.example.com/page1436.html
http://www.example.com/page1730.html
【やりたいこと】
aタグのついたURLとtd属性の文字を同時に取得したいです。別々に表示されるのではなく下記のようにそれぞれが対で表示されることが望ましいです。
http://www.example.com/page1234.html 105-0004 東京都港区新橋1-2-3
http://www.example.com/page1236.html 105-0004 東京都港区新橋2-3-4
http://www.example.com/page1366.html 105-0004 東京都港区新橋4-5-6
http://www.example.com/page1436.html 105-0006 東京都港区芝1-23-3
http://www.example.com/page1730.html 105-0007 東京都港区芝5-20-1
【試したこと】
<?php require_once 'goutte.phar'; $client = new \Goutte\Client(); // まずフォームのあるURLにアクセス $crawler = $client->request('GET', 'http://www.example.com/form.php''); // 「Btn1」というボタンクリックで送信されるフォームを選択 $form = $crawler->selectButton('Btn1')->form(); $crawler = $client->submit($form, array()); $URL = $crawler->filter("table.small a")->each(function ($node){ echo $node->attr('href'); // attr->('attribute') //URL取得 } $ADDRESS = $crawler->filter("table.small td")->each(function ($node){ echo $node->text(); // プレーンテキストを取得 }); ?>としてみたのですが、取れませんでした。
$crawler->filter("table.small a")->each(function ($node)あたりの記載方法を変えればよさそうと思っているのですが、いろいろ試しましたがうまくいきません。
どのように記載すれば両方を取得できるのか教えてください。
よろしくお願いいたします。
追記
有難うございます。
テーブルは下記となります。
name="small" ではなく class="small" でした。大変失礼いたしました。
回答2件
あなたの回答
tips
プレビュー