#javascript #applescript
#javascript #applescript
Вопрос:
Мне приходится анализировать около 30 рекламных папок магазина каждую неделю. В настоящее время я знаю, где найти папку HTML наизусть, но все равно мне приходится переписывать URL из каждого руководства по размещению, которое я хотел бы автоматизировать.
У меня есть возможность использовать только AppleScript или, возможно, JavaScript (на моем хостинге MobileMe нет PHP eo.)
В URL есть несколько переменных:
http://store.website.com/[store]/[region]/[date]NL/[store]_[region]_[date]NL.pdf
Я бы хотел, чтобы это работало следующим образом:
-
Диалоговое окно из или, в котором меня просят сообщить
a. Хранилище: [заполнить хранилище];
b. Регион: [заполнить регион];
c. Дата: [заполнить дату]. -
Загрузите файл и сохраните на
//specific/path
моем компьютере.
Я новичок в AppleScript и JavaScript, но я не могу использовать PHP / SQL, поэтому я надеюсь, что кто-нибудь может помочь мне показать некоторые другие направления.
Ответ №1:
AppleScript (загружается на ваш рабочий стол):
display dialog "Store?" default answer ""
set the Store_Input to the text returned of the result
display dialog "Region?" default answer ""
set the Region_Input to the text returned of the result
display dialog "Date?" default answer ""
set the Date_Input to the text returned of the result
set link to "http://store.website.com/" amp; Store_Input amp; "/" amp; Region_Input amp; "/" amp; Date_Input amp; "NL/" amp; Store_Input amp; "_" amp; Region_Input amp; "_" amp; Date_Input amp; "NL.pdf"
set the destination to ((path to desktop as string) amp; Store_Input amp; "_" amp; Region_Input amp; "_" amp; Date_Input amp; "NL.pdf")
tell application "URL Access Scripting"
download link to destination replacing yes
end tell
Ответ №2:
Энн дала вам хороший скрипт, однако я полагаю, что вы можете сделать это очень просто для себя. Я предполагаю, что магазин всегда связан с регионом и веб-сайтом, поэтому вы можете ввести эту информацию в скрипт, а затем просто выбрать ее из списка вместо того, чтобы вводить каждый раз.
Таким образом, вам необходимо создать список записей с этой информацией. Я ввел для вас 4 примера в storeRegionRecord в верхней части скрипта. Вам также необходимо ввести путь к папке в переменной downloadFolder, куда должны быть загружены файлы.
Вот как работает скрипт после ввода информации, как описано. Появится диалоговое окно, в котором вы можете выбрать одну или несколько комбинаций магазина / региона / веб-сайта для загрузки. Вы бы выбрали больше 1, если бы дата применялась к нескольким из них. Нажмите Shift или Command, чтобы выбрать более 1 в диалоговом окне. Затем появляется второе диалоговое окно, в котором вы вводите конкретную дату. Повторный цикл проходит по выбранному вами магазину / региону / веб-сайтам и загружает каждый PDF-файл в папку загрузки, называя загруженный PDF-файл так, как Энн предложила в своем коде.
Я надеюсь, это поможет…
property storeRegionRecord : {{store:"store1", region:"region1", website:"http://store1.website.com/"}, {store:"store2", region:"region2", website:"http://store2.website.com/"}, {store:"store3", region:"region3", website:"http://store3.website.com/"}, {store:"store4", region:"region4", website:"http://store4.website.com/"}}
property aDate : ""
property listDelimiter : "*"
set downloadFolder to path to desktop as text
-- get the store/region/website to download. You can choose more than 1.
set chooseList to chooseListForStoreRegionRecord(storeRegionRecord)
choose from list chooseList with title "PDF Downloads" with prompt "Choose one or more..." default items (item 1 of chooseList) OK button name "Select" cancel button name "Quit" with multiple selections allowed
tell result
if it is false then error number -128 -- cancel
set selectedItems to items
end tell
-- enter the date
display dialog "Date?" default answer aDate
set aDate to the text returned of the result
-- download the files
set text item delimiters to listDelimiter
repeat with aSelection in selectedItems
set theVariables to text items of aSelection
set theStore to item 1 of theVariables
set theRegion to item 2 of theVariables
set theWeb to item 3 of theVariables
if theWeb does not end with "/" then set theWeb to theWeb amp; "/"
set link to theWeb amp; theStore amp; "/" amp; theRegion amp; "/" amp; aDate amp; "NL/" amp; theStore amp; "_" amp; theRegion amp; "_" amp; aDate amp; "NL.pdf"
set destination to downloadFolder amp; theStore amp; "_" amp; theRegion amp; "_" amp; aDate amp; "NL.pdf"
tell application "URL Access Scripting" to download link to file destination replacing yes
end repeat
set text item delimiters to ""
-- tell me that it's finished
display dialog "The PDF files were downloaded to:" amp; return amp; (downloadFolder as text) buttons {"OK"} default button 1 with icon note
(*============= SUBROUTINES ===============*)
on chooseListForStoreRegionRecord(storeRegionRecord)
set chooseList to {}
repeat with aRecord in storeRegionRecord
set end of chooseList to store of aRecord amp; listDelimiter amp; region of aRecord amp; listDelimiter amp; website of aRecord
end repeat
return chooseList
end chooseListForStoreRegionRecord