PHPプログラムに関する各種メモ書き

phpでxpathを使ってスクレイピング(WEBページの取得)とXpathの書式例

■ 1. まず php-xml のインストール

yum install php-xml

■ 2. 実際のサイトからスクレイピングを行って Xpath で要素を取得のPHPコード

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 );

■ 3. Xpath書式例

全要素

//*	または /descendant::*

全 div 要素

//div	または /descendant::div

HTMLページのタイトル

//html/head/title

全 li または div 要素

//*[name()='li' or name()='div' ]

class 属性が 'hoge' な div 要素(完全一致)

//div[@class='hoge']	/descendant::div[@class='hoge']

class 属性が 'hoge fuga' な div 要素(完全一致)

//div[@class='hoge fuga']
//div[contains(@class ,'hoge') and contains(@class ,'fuga')]

class 属性に 'list' を含む div 要素(部分一致)

//li[contains(@class,'list')]

そのノードのテキストの取得

//div[@class='hoge']/text()

そのノード以下の全てのテキストの取得

//div[@class='hoge']/.

id 属性が 'hoge' な要素 → id('hoge')と書くのが高速ですがPHPではうまく取得できないこともあります

id('hoge')
//*[@id='hoge']
/descendant::*[@id='hoge']

テキストが 'hogehoge' なdiv要素(完全一致)   例:<div>hogehoge</div>

//div[text()='hogehoge']

テキストが 'fuga' を含むdiv要素(部分一致)

//div[contains(text(), "fuga")]

【thタグ内のテキストが'fuga'】なthを持つ tr

//table//tr[th[text()='fuga']]

title 属性が 'hoge' で class 属性が 'fuga' でない要素

//*[@title='hoge' and @class!='fuga']
/descendant::*[@title='hoge' and @class!='fuga']

form 要素の 3 番目の input 要素

//form/descendant::input[3]	/descendant::form/descendant::input[3]

5番目以降の p 要素

//p[position() >=5]

チェックされたチェックボックスの親要素

***//input[@checked='checked']/.. //input[@checked='checked']/parent::node()

RSSフィードのURL

//link[@rel="alternate" and @type="application/rss+xml"]/@href

src が 'images/test.gif' の要素

//*[@src='images/test.gif' ]

img タグで src に 文字列 .gif を含む要素

//img[contains(@src, '.gif')]

Firefox xpath アドオン(右クリックで xpath を表示)

https://addons.mozilla.org/en-US/firefox/addon/xpath-checker/

Xpathの書式

http://itref.fc2web.com/xml/xpath.html

Xpath仕様

http://www.w3.org/TR/xpath/

関連エントリー

No.723
12/08 14:07

edit

Xpath