LoginSignup
25
26

More than 5 years have passed since last update.

Simple HTML DOM Parserを使ったスクレイピング

Posted at

Simple HTML DOM parserのインストール

ここ(http://sourceforge.net/projects/simplehtmldom/files/)から
simple_html_dom.phpをダウンロードしてスクリプトと同フォルダ内に保存する。

<?php
include "simple_html_dom.php";
$html = file_get_html('http://www.google.com/');
foreach($html->find('img') as $element){
       echo $element->src . "<br>";
}

Simple HTML DOM parserの使い方

http://simplehtmldom.sourceforge.net/manual.htm

1.URLからDOMを作成

$html = file_get_html(http://www.google.com/'); 

2.DOMから特定要素の抽出

// img要素のソースURLの抽出
foreach($html->find(img) as $element){
    echo $element->src.<br>;
}

// a要素のhref属性の抽出
foreach($html->find(a) as $element){
    echo $element->href.<br>;
}


//属性による抽出対象の指定
foreach($html->find(a[title=top]) as $element){
    echo $element->href.<br>;
}

//classによる抽出対象の指定
$es = $html->find(table.hello td);



//階層の指定
$es = $html->find(table td[align=center]);


//ネスト
foreach ($html->find(div[id=new] as $div1){
    foreach($div1->find(p[title] as $p1){
        echo $p1->plaintext;
    }
}


3.DOMに属性の設定

// img要素の拡張子をjpgからpngに変更
foreach($html->find(img) as $img){
    $img->src = str_replace(jpg,png,$img->src);
}

25
26
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
25
26