ブラウザで画像が表示されていても、そのリンク先のURLから直接画像を保存できない場合があります。
ユーザーエージェントか何からしら、ブラウザで見ているかどうかをチェックしているのだと思います。
そんな時に、Apple Script と Safari と PHP を使った画像の保存方法。
まず、Macのターミナルから右クリックが実行できるように、「Mouse Clicks」を入れておく。
次に、画像を表示する簡単な 「index.php」 を作ってサーバーに置く(localhost下でもよい)。
$url = "";
if(isset($_GET["url"])){
$url = $_GET["url"];
}else{
return;
}
<html>
<head>
<title>Sample</title>
<style>
*{
padding: 0;
margin: 0;
}
</style>
</head>
<body>
<img src="<?php echo $url; ?>" />
</body>
</html>
次に、Apple Script を書く。
property repeatCount : 20
property delayTime : 0.5
on run argv
tell application "Finder"
activate
display dialog "画像のURL を入力してください" default button 2 default answer ""
set tmpText to result
set url1 to text returned of tmpText
end tell
tell application "Safari" to activate
tell application "System Events"
tell process "Safari"
set frontmost to true
click menu item "新規ウインドウ" of menu "ファイル" of menu bar 1
end tell
end tell
tell application "Safari"
tell window 1
set bounds to {50, 30, 300, 300}
end tell
end tell
set url1 to "http://localhost/index.php?url=" & url1
tell application "Safari"
do JavaScript "
(function() {
location.href = '" & url1 & "'
}());
" in document 1
my isLoaded(url1)
end tell
delay 1
do shell script "MouseTools -x 200 -y 200 -rightClick"
delay 0.5 -- 右クリックからコンテキストメニューが出てくるまで、10秒くらいかかることもある
tell application "System Events"
key code 125 -- Arrow Down
key code 125 -- Arrow Down
key code 125 -- Arrow Down
--・・・ コンテキストメニューの「イメージをダウンロードに保存」まで繰り返す
keystroke return -- Enter Key
end tell
end run
on isLoaded(url1)
tell application "Safari"
repeat my repeatCount times
if URL of document 1 contains url1 then
repeat my repeatCount times
if (do JavaScript "res = (function() {return document.readyState}());" in document 1) is "complete" then
return true
end if
delay my delayTime
end repeat
return false
end if
delay my delayTime
end repeat
return false
end tell
end isLoaded
この Apple Script を実行すると、
画像のURLを入力 → Safariブラウザで、index.php に画像を表示 → 画像上で右クリック → イメージをダウンロードに保存
という流れになる。
画像が1個だけだと、右クリックで保存の方が早いと思いますが、
画像が何十個以上にもなると、このスクリプトを呼ぶ方が早くなるかもしれません。
追記 2020/05/21
「別名で保存」の場合は、右クリックした後、以下のようにする。
tell application "System Events"
key code 125 -- Arrow Down
key code 125 -- Arrow Down
key code 125 -- Arrow Down
key code 125 -- Arrow Down
keystroke return -- Enter Key
keystroke "ファイル名"
keystroke return -- Enter Key
end tell
追記 2020/05/23
画像を選択したときに、右クリックのメニューの内容が変わることがあった。
メニューの一番上に、「新規タブで”〜.jp”」を開く、「新規ウィンドウで”〜.jp”」を開くの2つが追加されている。(※原因は不明)
これでは、「イメージを別名で保存」のメニューが上から何番目かがわからないので、キーボードの下を押す作戦が使えない。
逆の発想で、上キーを押したら、一番下のメニューから始まったので、下からメニューを選択する。
tell application "System Events"
key code 126 -- Arrow Up
key code 126 -- Arrow Up
key code 126 -- Arrow Up
key code 126 -- Arrow Up
key code 126 -- Arrow Up
key code 126 -- Arrow Up
key code 126 -- Arrow Up
keystroke return -- Enter Key
keystroke "ファイル名"
keystroke return -- Enter Key
end tell