LoginSignup
16
19

More than 5 years have passed since last update.

破天荒なHTMLでもスクレイピングする

Last updated at Posted at 2017-01-18

「破天荒な」というのは、文法的にめちゃくちゃなHTMLのことではあるのですが、閉じタグがないとかまあ、そういうHTMLですね。

めちゃくちゃなHTMLでもチェックツールはあるんだし、なにかモジュールでも使って正しく整形しちゃえばスクレイピングできちゃうんじゃないの?と思って、調べて見るとありました。

tidy

HTMLをチェックして、整形する機能なんですねー。

基本的にスクレイピング案件なんて、手をつけないので、利用する機会はないと思う。「他人の褌で…」というのが性に合わない…。ただ、被スクレイピング対策に破天荒なHTMLを書いて、パースしにくくするという対策は効かないんだな、ということはわかった。

うまくいかない場合のサンプル

実際に破天荒なHTMLのサイトがあれば、それで実験して見たいとは思ったのですが、ググったところで見つかるわけはないだろうと思うので、以下のサンプルで。

<?php

ini_set('display_errors', true);
error_reporting(E_ALL);

$html = <<<HTML
<!DOCTYPE HTML>
<html lang="ja">
    <head>
        <meta charset="UTF-8">
        <title>タイトル</title>
    </head>
    <body>
    <div>
    <ul>
        <span>span</span>
        <div>
            <li>li1</li>
            <li>li2
            <li>li3</li>
    </body>
</html>
HTML;

$res = simplexml_load_string($html);
var_dump($res);

対策済みのサンプル

<?php

ini_set('display_errors', true);
error_reporting(E_ALL);

$html = <<<HTML
<!DOCTYPE HTML>
<html lang="ja">
    <head>
        <meta charset="UTF-8">
        <title>タイトル</title>
    </head>
    <body>
    <div>
    <ul>
        <span>span</span>
        <div>
            <li>li1</li>
            <li>li2
            <li>li3</li>
    </body>
</html>
HTML;

$config = array(
    'drop-empty-elements' => false, // 空の要素を削除しない
    'hide-comments' => true, // コメントを削除
    'output-xhtml' => true, // xhtml に変換
);

$tidy = new tidy();
$tidy->parseString($html, $config, 'utf8');
$tidy->cleanRepair();

$res = simplexml_load_string($tidy);
var_dump($res);
16
19
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
16
19