aoma blog

エンジニアの日常とか技術とか

JavaScriptで一覧ページの画像URLを全て取得する

この記事は移転しました。約5秒後に新記事へ移動します。
移動しない場合はココをクリックして新サイトをお楽しみください。

稀に、一覧ページとかに表示されてる画像URLを全て取得したいとき、あるよねー!

そんなときは Chromeデベロッパーツールを使いましょう。

JS pathを取得

Copy JS pathで取得

document.querySelector("#qurireco > article:nth-child(1) > a > div > div._7uaWVw_YSgf_GKoctUM12 > span > img")

こんな感じ。

f:id:aoma23:20191125160708p:plain

getAttributeで画像URLが取得できることを確認

Consoleタブに貼り付けて確認してみる。

console.log(document.querySelector("#qurireco > article:nth-child(1) > a > div > div._7uaWVw_YSgf_GKoctUM12 > span > img").getAttribute("src"));

JS pathの規則性を探す

document.querySelector("#qurireco > article:nth-child(1) > a > div > div._7uaWVw_YSgf_GKoctUM12 > span > img")
document.querySelector("#qurireco > article:nth-child(2) > a > div > div._7uaWVw_YSgf_GKoctUM12 > span > img")
document.querySelector("#qurireco > article:nth-child(3) > a > div > div._7uaWVw_YSgf_GKoctUM12 > span > img")

nth-childのカッコ内の数字が違う感じだなー。

ループさせる要素を見つける

上記でみつけた規則性から下記要素をループすれば良さそう。

document.querySelectorAll("#qurireco > article")

素数を確認

念の為件数を確認。

console.log(document.querySelectorAll("#qurireco > article").length);

ループして出力

var elements = document.querySelectorAll("#qurireco > article");
for (var element of elements) {
  console.log(element.querySelector("a > div > div._7uaWVw_YSgf_GKoctUM12 > span > img").getAttribute("src"));
}

クリップボードにコピーするのも良き

var elements = document.querySelectorAll("#qurireco > article");
var list = [];
for (var element of elements) {
  list.push(element.querySelector("a > div > div._7uaWVw_YSgf_GKoctUM12 > span > img").getAttribute("src"));
}
copy(list.join("\n"));

かんたんですね!