Last active
March 12, 2021 05:47
-
-
Save fddcddhdd/4d54099e3f3559f01b50517d78eeae9a to your computer and use it in GitHub Desktop.
PHPでamazonのWebスクレイピングをしてみた。最新コミック未来と過去の30日以内を取得できた。
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// 50ページ目(24冊✕50ページ=1200冊)までしか表示されなかった | |
for($i=1; $i < 50+1; $i++){ | |
// コンテンツを取得 | |
$ch = curl_init(); | |
curl_setopt_array($ch, [ | |
CURLOPT_URL => 'https://www.amazon.co.jp/s/?rh=n%3A465392%2Cn%3A%21465610%2Cn%3A466280%2Cn%3A2278488051%2Cp_n_publication_date%3A2285541051&sort=date-asc-rank&unfiltered=1&page=' . $i, // 未来30日以内 | |
// CURLOPT_URL => 'https://www.amazon.co.jp/s/?rh=n%3A465392%2Cn%3A%21465610%2Cn%3A466280%2Cn%3A2278488051%2Cp_n_publication_date%3A82837051&sort=date-asc-rank&unfiltered=1&page=' . $i, // 過去30日以内 | |
CURLOPT_RETURNTRANSFER => true, | |
CURLOPT_FOLLOWLOCATION => true, | |
CURLOPT_AUTOREFERER => true, | |
CURLOPT_USERAGENT => 'Mozilla/5.0', | |
CURLOPT_ENCODING => 'gzip', | |
]); | |
$html = curl_exec($ch); | |
// エラーを出さずにDOMDocumentに読み込む | |
$dom = new DOMDocument; | |
@$dom->loadHTML(mb_convert_encoding($html, 'HTML-ENTITIES', 'UTF-8')); | |
// DOMDocumentからXPath式を実行するためのDOMXPathを生成 | |
$xpath = new DOMXPath($dom); | |
// class属性値にs-result-itemを含むli要素を全ノードから検索する | |
foreach ($xpath->query('//li[contains(@class, "s-result-item")]') as $li) { | |
// class属性値に所定の値を含む所定の要素を各li要素の中から検索する | |
// 各情報をまとめて配列にし、更にその配列を$items配列の要素として代入する | |
$detail_page = $xpath->evaluate('string(.//a[contains(@class, "s-access-detail-page")]/@href)', $li); | |
// https://www.amazon.co.jp/dp/ にくっつけるID(実際の本だとISBN、kindleだとASINみたい) | |
if(preg_match('/\/dp\/(.+?)\//', $detail_page, $match)){ | |
$amazon_dp = $match[1]; | |
echo $amazon_dp ."<br>\n"; | |
} | |
} | |
// サーバ負荷を下げるためのWait | |
usleep(500); | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment