composer require vdb/php-spider
<?php
use VDB\Spider\Spider;
use VDB\Spider\Discoverer\XPathExpressionDiscoverer;
use VDB\Spider\StatsHandler;
require_once "./vendor/autoload.php";
$spider = new Spider('https://google.co.jp/');
// $spider->getDiscovererSet()->set(new XPathExpressionDiscoverer("//div"));
$spider->getDiscovererSet()->maxDepth = 3;
$spider->getQueueManager()->maxQueueSize = 10;
// $statsHandler = new StatsHandler();
// $spider->getQueueManager()->getDispatcher()->addSubscriber($statsHandler);
// $spider->getDispatcher()->addSubscriber($statsHandler);
$spider->crawl();
foreach ($spider->getDownloader()->getPersistenceHandler() as $resource) {
echo "\n" . $resource->getCrawler()->filterXpath('//div')->text() ."\n";
}
インストールするディレクトリ(CodeIgniterの場合は /codeigniter/application/)に移動しターミナルから
composer require querypath/querypath
でインストール。
CodeIgniterを使用している場合は config/config.php の
$config['composer_autoload'] = TRUE;
で自動的に読み込まれます。
Laravel を使用している場合は何もしなくても自動的に読み込まれます。
フレームワークを使用していない場合は
require_once "vendor/autoload.php";
require_once "vendor/autoload.php";
$url = 'http://yahoo.co.jp/';
$html = file_get_contents($url);
$qp = html5qp($html);
print qp($html, 'title')->text();
print qp($html, 'meta[name=description]')->attr("content");
TidyとはHTMLタグの閉じ忘れを直したりHTML修正を行う便利なソフトです。
Xpathでスクレイピングを行うときにHTMLが完璧でないと正しく取得できないので事前に整形を行います。
なおPECL拡張なのでインストールにはサーバー管理者権限が必要です。
yum install php-tidy
apachectl graceful
$html = '<html><body><p>タグの閉じ忘れテスト</body></html>'; if ( ! in_array('tidy',get_loaded_extensions(), true )){ die('このサーバではtidyが使用できません'); } $config = array('indent' => false, 'output-xhtml' => TRUE, 'wrap' => 200); $tidy = tidy_parse_string($html, $config, 'UTF8'); $h = tidy_get_html($tidy); $html = $h->value;
以上の簡単なコードで実現できますが、整形するソースファイルが大きいとメモリ、プロセス共に大量に使用するので注意。
$configに設定できるオプションはこちら
http://tidy.sourceforge.net/docs/quickref.html
XMLファイルからHTMLファイルを作成したい時、XSLTを使うと早い場合があります。
そのサンプル
<?php $xml = new DomDocument(); $xml->load('test.xml'); $xsl = new DomDocument(); $xsl->load('sample01.xsl'); $processor = new xsltprocessor(); $processor->importStyleSheet($xsl); echo $processor->transformToXML($xml); ?>
http://vosegus.org/guideline/xslt.html
<xsl:if test="contains(./text() , 'hoge')"> ZZZZZZZZZ </xsl:if>
<xsl:param name="contents">デフォルト値</xsl:param>
yum install php-xml
test.server.com から WEBページを取得してきて<div id="myid">の要素を取得します。
$url='http://test.server.com'; // file_get_contents を使うより高速、ただしメモリは食う require_once 'HTTP/Client.php'; $client =& new HTTP_Client(); $client->get($url); $response = $client->currentResponse(); $dom = @DOMDocument::loadHTML( $response['body']); $xml = simplexml_import_dom($dom); $t = $xml->xpath('id("myid")'); if (! $t){ die('xpath error'); } print_r( $t );
//* または /descendant::*
//div または /descendant::div
//html/head/title
//*[name()='li' or name()='div' ]
//div[@class='hoge'] /descendant::div[@class='hoge']
//div[@class='hoge fuga'] //div[contains(@class ,'hoge') and contains(@class ,'fuga')]
//li[contains(@class,'list')]
//div[@class='hoge']/text()
//div[@class='hoge']/.
id('hoge') //*[@id='hoge'] /descendant::*[@id='hoge']
//div[text()='hogehoge']
//div[contains(text(), "fuga")]
//table//tr[th[text()='fuga']]
//*[@title='hoge' and @class!='fuga'] /descendant::*[@title='hoge' and @class!='fuga']
//form/descendant::input[3] /descendant::form/descendant::input[3]
//p[position() >=5]
***//input[@checked='checked']/.. //input[@checked='checked']/parent::node()
//link[@rel="alternate" and @type="application/rss+xml"]/@href
//*[@src='images/test.gif' ]
//img[contains(@src, '.gif')]
https://addons.mozilla.org/en-US/firefox/addon/xpath-checker/
http://itref.fc2web.com/xml/xpath.html
http://www.w3.org/TR/xpath/