我需要在AppleScript中对字符串进行URL编码

时间:2014-05-25 04:59:24

标签: applescript urlencode

我的脚本在网站上搜索歌曲,但是当有空格时它不会搜索,你必须添加下划线。我想知道是否有办法用下划线替换我的空间。 您可以使用我目前的代码向我展示如何操作吗?

set search to text returned of (display dialog "Enter song you wish to find" default answer "" buttons {"Search", "Cancel"} default button 1)
open location "http://www.mp3juices.com/search/" & search
end

8 个答案:

答案 0 :(得分:3)

尝试以下方法:

set search to text returned of (display dialog "Enter song you wish to find" default answer "" buttons {"Search", "Cancel"} default button 1)
  do shell script "open 'http://www.mp3juices.com/search/'" & quoted form of search
end

您需要的是 URL编码(即,安全包含在URL中的字符串编码),这不仅仅是替换空格。 谢天谢地,open命令行实用程序会为您执行此编码,因此您可以直接将字符串传递给它;您需要do shell script来调用openquoted form of确保字符串通过未经修改的传递(稍后由open进行URI编码)。

正如您所看到的,编码open的网址类型会使用%20替换空格,而不是下划线,但这仍然有用。

答案 1 :(得分:2)

mklement0&#39的答案是正确的url编码,但mp3juices使用RESTful URL(干净的URL)。 RESTful URL希望保持URL的可读性,并且您不会在显示ASCII号码的网址中看到/使用典型的十六进制值。正如您所提到的,snake_case(是假的),但在RESTful URL中使用替换空格(%20)(和其他字符)是很常见的。但是,在通过标准URL编码处理RESTful之前,必须将RESTful的slug转换为RESTful自己的RESTful编码。

set search to text returned of (display dialog "Enter song you wish to find" default answer "" buttons {"Search", "Cancel"} default button 1)
set search to stringReplace(search, space, "-")
do shell script "open 'http://www.mp3juices.com/search/'" & quoted form of search

on stringReplace(theText, searchString, replaceString)
    set {oldTID, AppleScript's text item delimiters} to {AppleScript's text item delimiters, searchString}
    set textItems to every text item of theText
    set AppleScript's text item delimiters to replaceString
    set newText to textItems as string
    set AppleScript's text item delimiters to oldTID
    return newText
end stringReplace

编辑:更新代码,不像提到空格转换为下划线的问题,mp3juice使用连字符作为空格的替换。

答案 2 :(得分:2)

对此的更新,尽管答案是3年,因为我面临同样的问题:在最新版本的macOS / OS X / Mac OS X(我认为,10.10或更高版本),你可以使用ASOC,AppleScript / Objective-C桥:

use framework "Foundation"

urlEncode("my search string with [{?@äöü or whatever characters")

on urlEncode(input)
    tell current application's NSString to set rawUrl to stringWithString_(input)
    set theEncodedURL to rawUrl's stringByAddingPercentEscapesUsingEncoding:4 -- 4 is NSUTF8StringEncoding
    return theEncodedURL as Unicode text
end urlEncode

应该注意的是,stringByAddingPercentEscapesUsingEncoding已被弃用,但从macOS中移除它需要一些时间。

答案 3 :(得分:1)

如果您需要以字符串形式获取URL(而不仅仅是将其输入open中,它会为您完成出色的编码工作) ,那么您不需要花太多时间Automator,您可以在AppleScript中添加一些JavaScript:

enter image description here enter image description here enter image description here

encodeURIComponent是内置的JavaScript函数-它是编码URI组件的完整解决方案。

对于复制/粘贴,以下是上述Automator链中的所有三个脚本:

on run {input, parameters}
    return text returned of (display dialog "Enter song you wish to find" default answer "" buttons {"Search", "Cancel"} default button 1)
end run
function run(input, parameters) {
    return encodeURIComponent(input);
}
on run {input, parameters}
    display dialog "http://www.mp3juices.com/search/" & input buttons {"okay!"} default button 1
end run

答案 4 :(得分:0)

URL encoding在AppleScript中

在一般情况下(对于我来说,目前将包含#&ßö等字符的任何ASCII URL传递给{{3 }}),我偶然发现了一个不错的代码段,该代码段立即为我的ShortURL剪贴板粘贴bit.ly API添加了全部支持。这是shortcut的引文:

  

我一直在寻找一种快速而肮脏的方式来编码一些数据,以通过applescript和Internet Explorer通过POST或GET传递到url,有一些OSAXen具有这种能力,但是我不想安装任何东西,所以我写了这本书(使用标准的ascii字符,高于ascii 127的字符可能会遇到字符集问题,请参见:source

注释

代码

on urlencode(theText)
    set theTextEnc to ""
    repeat with eachChar in characters of theText
        set useChar to eachChar
        set eachCharNum to ASCII number of eachChar
        if eachCharNum = 32 then
            set useChar to "+"
        else if (eachCharNum ≠ 42) and (eachCharNum ≠ 95) and (eachCharNum < 45 or eachCharNum > 46) and (eachCharNum < 48 or eachCharNum > 57) and (eachCharNum < 65 or eachCharNum > 90) and (eachCharNum < 97 or eachCharNum > 122) then
            set firstDig to round (eachCharNum / 16) rounding down
            set secondDig to eachCharNum mod 16
            if firstDig > 9 then
                set aNum to firstDig + 55
                set firstDig to ASCII character aNum
            end if
            if secondDig > 9 then
                set aNum to secondDig + 55
                set secondDig to ASCII character aNum
            end if
            set numHex to ("%" & (firstDig as string) & (secondDig as string)) as string
            set useChar to numHex
        end if
        set theTextEnc to theTextEnc & useChar as string
    end repeat
    return theTextEnc
end urlencode

答案 5 :(得分:0)

我在寻找 URL 编码和解码时遇到了这个 helpful link

你可以像这样使用:

set theurl to "https://twitter.com/zackshapiro?format=json"
do shell script "php -r 'echo urlencode(\"" & theurl & "\");'"
# gives me "https%3A%2F%2Ftwitter.com%2Fzackshapiro%3Fformat%3Djson"

set theurl to "https%3A%2F%2Ftwitter.com%2Fzackshapiro%3Fformat%3Djson"
return do shell script "php -r 'echo urldecode(\"" & theurl & "\");'"
# gives me "https://twitter.com/zackshapiro?format=json"

或作为函数:

on encode(str)
    do shell script "php -r 'echo urlencode(\"" & str & "\");'"
end encode

on decode(str)
    do shell script "php -r 'echo urldecode(\"" & str & "\");'"
end decode

答案 6 :(得分:0)

据说,AppleScriptObjC 允许我们使用 NSString 进行编码。由于 URL 的不同部分允许使用不同的字符(我已经为所有这些字符添加了选项),因此脚本很复杂,但在大多数情况下,将使用“查询”选项。

有关各种 URL 部分的说明,请参阅 NSCharacterSet's dev page(称为“获取 URL 编码的字符集”的部分)。

use AppleScript version "2.4" -- Yosemite 10.10 or later
use framework "Foundation"

property NSString : class "NSString"
property NSCharacterSet : class "NSCharacterSet"

-- example usage
my percentEncode:"some text" ofType:"query"

on percentEncode:someText ofType:encodeType
    set unencodedString to NSString's stringWithString:someText
    set allowedCharSet to my charSetForEncodeType:encodeType
    set encodedString to unencodedString's stringByAddingPercentEncodingWithAllowedCharacters:allowedCharSet
    return encodedString as text
end percentEncode:ofType:

on charSetForEncodeType:encodeType
    if encodeType is "path" then
        return NSCharacterSet's URLPathAllowedCharacterSet()
    else if encodeType is "query" then
        return NSCharacterSet's URLQueryAllowedCharacterSet()
    else if encodeType is "fragment" then
        return NSCharacterSet's URLFragmentAllowedCharacterSet()
    else if encodeType is "host" then
        return NSCharacterSet's URLHostAllowedCharacterSet()
    else if encodeType is "user" then
        return NSCharacterSet's URLUserAllowedCharacterSet()
    else if encodeType is "password" then
        return NSCharacterSet's URLPasswordAllowedCharacterSet()
    else
        return missing value
    end if
end charSetForEncodeType:

答案 7 :(得分:0)

Python 方法:

  1. 找到您的 python3 路径 (which python3),如果您没有,请使用 brew 或 miniconda 安装
  2. 现在试试这个:

python_path = /path/to/python3

set search_query to "testy test"

tell application "Google Chrome"
    set win to make new window
    open location "https://www.google.com/search?q=" & url_encode(q)
end tell

on url_encode(input)
    return (do shell script "echo " & input & " | " & python_path & " -c \"import urllib.parse, sys; print(urllib.parse.quote(sys.stdin.read()))\"
")
end url_encode

感谢@Murphy https://stackoverflow.com/a/56321886