2012-02-01 64 views
0

我想要一個腳本在Google上搜索當前播放歌曲的歌詞。爲什麼以下不工作?AppleScript:搜索Google for iTunes歌詞

tell application "iTunes" 
    set trackArtist to artist of current track 
    set trackName to name of current track 
end tell 
set search to trackArtist & " - " & trackName & " lyrics" 
open location "https://www.google.com/search?q=" & search 

如果我「返回搜索」,我可以看到變量設置正確。如果我在最後一行用「測試歌詞」替換「搜索」,瀏覽器將按預期打開。但上面的腳本不會執行任何操作,也不會返回任何錯誤。

回答

1

我想你忘了大多數瀏覽器在地址欄中解碼URL,並且在請求之前再次對URL進行編碼。所以你需要做的是對網址進行編碼。

tell application "iTunes" 
    set trackArtist to artist of current track 
    set trackName to name of current track 
end tell 
open location "http://www.google.com/search?q=" & rawurlencode(trackArtist & " - " & trackName & " lyrics") 

on rawurlencode(theURL) 
    set PHPScript to "<?php echo rawurlencode('%s');?>" 
    set theURL to do shell script "echo " & quoted form of theURL & " | sed s/\\'/\\\\\\\\\\'/g" 
    return do shell script "printf " & quoted form of PHPScript & space & quoted form of theURL & " | php" 
end rawurlencode 
+0

奇妙!謝謝。我從來不知道如何編碼。我想知道爲什麼sed需要這麼多的斜槓s/\\'\/\\\\\\\\'/ g – Zade 2012-02-02 00:47:30

+0

是的,我知道sed命令很混亂。每次你進入一個新的環境時,你都需要在AppleScript中跳過反斜槓,所以它會是2,但是當需要的時候它會是4,最終我們需要在php中轉義單引號,因此我們需要8(2^3 = 8)。正如你所看到的,即使是名字中帶有單引號的歌曲或藝術家也會被正確編碼。如果我們不以這種方式使用sed命令,則不會發生這種情況。 – 2012-02-02 02:12:40