環境
Mac OS X 10.4.11 (PPC; 日本語優先)
Safari 3.0.4
Amazon の
http://www.amazon.co.jp/商品名/dp/ASINコード/ref=ずらずらずらずら...
などという URL を短くして
http://www.amazon.co.jp/dp/ASINコード
にするときに、今までは
javascript:location.href=('http://www.amazon.co.jp/dp'+document.URL.match(/\/[0-9a-zA-Z]{10}(?:\/*|$)/))
というブックマークレットを実行して ASIN を取得していたのですが、これは URL 文字列のうち「スラッシュ + 10 個の [:alnum:] + スラッシュまたは行末」という正規表現に最初にマッチしたものを見ているだけです。
ということはもし 10 個の [:alnum:] で表記された商品名があるとして、それが URL 中で ASIN より先に来ていたらアウトだなと気がつきました。
では dp/ASIN という文字列を探して後方参照すれば良いかというと、...gp/product/ASINコード... なんて URL もあったりして (というかこっちが正式?) 厄介です。
面倒臭くなったので別の方法はないかとググってみました。
すると getElementsBy なんとかかんとか、というメソッドが。
使えそう。
javascript:location.href=('http://' + document.domain + '/dp/' + document.getElementsByName('ASIN')[0].value + '/')
document.domain というのも覚えたので使ってみました。
最初のスクリプトと比べて「関連商品を見る」のページから短縮できなかったりするのが残念ですが、ASIN が Amazon の商品識別番号であることを考えると、商品個別のページなら確実に getElementsByName('ASIN') を取得できるのではないかという気がします。
ついでに、ファイル名が商品の名前で始まる Webloc をデスクトップに作成する AppleScript。
タイトルの先頭にある Amazon.co... という文字列を削ってファイル名にします。URL はもちろん短縮済み。
set bs to «data utxt005C» as Unicode text
tell application "Safari"
try
set the_url to (URL of document 1)
if the_url starts with "http://www.amazon" then
set the_title to (name of document 1)
set sh_url to (do JavaScript "'http://' + document.domain + '/dp/' + document.getElementsByName('ASIN')[0].value + '/'" in document 1)
get {the_title, sh_url}
else
return
end if
on error
return
end try
end tell
set rbscript to "print $_.sub(/^Amazon" & bs & ".[" & bs & "w.]+." & bs & "s+/, '').gsub(/(?:^" & bs & ".|:)/, '-')"
set webloc_name to (do shell script "echo " & quoted form of the_title & " | ruby -Ku -ne " & quoted form of rbscript)
tell application "Finder"
make new internet location file at (path to desktop folder) to sh_url with properties {name:webloc_name}
end tell
tell application "Safari"
if not the_url is sh_url then
do JavaScript "location.href = '" & sh_url & "'" in document 1
end if
end tell