PHP Simple HTML DOM Parserを使用し、Google検索をWebスクレイピングしてみます。
■環境
・Windows10(Microsoft Edge)
・Visual Studio Code 1.53.2
・WampServer Version 3.2.3 64bit
・PHP Version 7.3.21
・Simple HTML DOM Parser Version1.9.1
■コード
<?php
include('simple_html_dom.php');
$html = file_get_html('https://www.google.com/');
echo $html->find('title',0) ->plaintext;
?>
■実行
このスクリプトを「hello.php」という名前で保存し、「simple_html_dom.php」のファイルが置かれているWampserver64内のフォルダ(C:\wamp64\www\project)に置きます。
置いた後に、Wampserver64を起動させます。
Warning: file_get_contents(https://www.google.com/): failed to open stream: HTTP request failed! HTTP/1.0 429 Too Many Requests in C:\wamp64\www\project\simple_html_dom.php on line 82
起動させた後に、Webブラウザで「http://localhost/project/hello.php」にアクセスしてみたのですが、「Warning」が表示されました。
■対処方法(Warning: file_get_contents(https://www.google.com/): failed to open stream: HTTP request failed! HTTP/1.0 429 Too Many Requests inという警告が発生)
「Warning: file_get_contents(https://www.google.com/): failed to open stream: HTTP request failed! HTTP/1.0 429 Too Many Requests in C:\wamp64\www\project\simple_html_dom.php on line 82」と表示される原因を調べましたが、これはスクリプトの問題ではなく、要求しているリソースの問題のようです。
またWebサーバーが「403 Forbiddenエラー」のステータスコードを返していることが問題のようです。スクレイピングを防ぐためにPHPスクリプトをブロックしたり、リクエストが多すぎる場合にIPをブロックがされたりする。(https://stackoverflow.com/questions/4545790/file-get-contents-returns-403-forbidden)
ユーザーエージェントを偽造し、google.comにリクエストを送信すればスクレイピングができるようですが、それでもうまくいきませんでした。よい解決方法があれば、追記していきます。
コメント