The following code has two lists: myURLs and myIMGs. I want to loop through the sites listed in myURLs, take a screenshot, then save them in my Shared folder as the file name listed in myIMGs. So, google.com's image will be saved as "google.jpg", and so forth. The list in myIMGs corresponds to the list in myURLs.
This is what I have, but it doesn't quite work. It loads the first URL from myURLs, takes a screenshot of it, but then loops through each file name in myIMGs and saves that one screenshot with all those various file names. Then, it loads the next URL in myURLs and does the same thing. How do I set the file names in the myIMGs list to correspond to the URLs being loaded from myURLs? I'm having trouble with the nested loops.
set myURLs to {"https://google.com", "https://wikipedia.org", "https://bing.com", "https://apple.com"}
set myIMGs to {"google.jpg", "wikipedia.jpg", "bing.jpg", "apple.jpg"}
-- Sets settings of Safari without interfering with user's settings.
repeat with myURL in myURLs
tell application "Safari"
set myDoc to front document
set windowID to id of window 1
do JavaScript ("window.open('" & myURL & "','_blank','titlebar=0');") in document 1
close window id windowID
set the bounds of the front window to {0, 20, 915, 812}
delay 5
end tell
-- Take screenshot, crop and save to Shared folder
repeat with myIMG in myIMGs
do shell script "screencapture -o -l$(osascript -e 'tell app \"Safari\" to id of window 1') /Users/Shared/" & myIMG
set this_file to "Macintosh HD:Users:Shared:" & myIMG
try
tell application "Image Events"
-- start the Image Events application
launch
-- open the image file
set this_image to open this_file
-- get dimensions of the image
copy dimensions of this_image to {W, H}
-- Crops off the Safari header
crop this_image to dimensions {W, H - 50}
-- save the changes
save this_image with icon
-- purge the open image data
close this_image
end tell
end try
end repeat
end repeat
You don't want to use two nested Repeat loops... you want to repeat and increment the variable n and then use item n of each list.
Here's the changed code... tested and works as expected:
set myURLs to {"https://google.com", "https://wikipedia.org", "https://bing.com", "https://apple.com"}
set myIMGs to {"google.jpg", "wikipedia.jpg", "bing.jpg", "apple.jpg"}
-- Sets settings of Safari without interfering with user's settings.
repeat with n from 1 to (count myURLs)
set myURL to item n in myURLs
tell application "Safari"
set myDoc to front document
set windowID to id of window 1
do JavaScript ("window.open('" & myURL & "','_blank','titlebar=0');") in document 1
close window id windowID
set the bounds of the front window to {0, 20, 915, 812}
delay 5
end tell
-- Take screenshot, crop and save to Shared folder
set myIMG to item n in myIMGs
do shell script "screencapture -o -l$(osascript -e 'tell app \"Safari\" to id of window 1') /Users/Shared/" & myIMG
set this_file to "Macintosh HD:Users:Shared:" & myIMG
try
tell application "Image Events"
-- start the Image Events application
launch
-- open the image file
set this_image to open this_file
-- get dimensions of the image
copy dimensions of this_image to {W, H}
-- Crops off the Safari header
crop this_image to dimensions {W, H - 50}
-- save the changes
save this_image with icon
-- purge the open image data
close this_image
end tell
end try
end repeat
You could simplify more by doing things like programmatically setting the file name based off of the URL string, and then you'd only have to maintain one list.
Related
I need a little help about an AppleScript script which for a folder of pictures :
Make a Selection out of already created path named Path 1
Then Crops the picture by that selection without Deleting the Cropped pixels
I have a problem finding the syntax in AppleScript to turn off "Deleting Cropped Pixels"..and looks like there is no such. I am lookin for a solution to save those pixels and a way to implement it in Applescript.
The solution i have uses key code commands and it's pretty inconvenient because "Delete Cropped Pixels" have to turned off manually in Photoshop before runing the script. Any OS notification outside PS will break the script.
tell application "Finder"
set ThePath to choose folder with prompt "Please select folder:"
set pictures_collection to every file of ThePath
end tell
repeat with anItem in pictures_collection
tell application "Adobe Photoshop CS6"
activate
set anItem to anItem as string
open file anItem
do action "Make_A_Selection" from "Make_A_Selection" -- runs an action with just makes the selection
set OpenedPicture to the current document
tell application "System Events"
-- The option "Delete Cropped Pixels" in the PS Crop tool is turned OFF manually so the next code do not erace the pixels
key code 8 -- press "C"
delay 0.5
key code 36 -- press "enter"
delay 0.5
key code 36 -- press "enter"
end tell
save OpenedPicture
close OpenedPicture
end tell
end repeat
return input
end run
So i looked for more efficient way but unfortunately i don't know how to implement the option not to "Delete Cropped Pixels" in the next script:
on run {input}
tell application "Finder"
set ThePath to choose folder with prompt "Please select folder:"
set pictures_collection to every file of ThePath
end tell
repeat with anItem in pictures_collection
tell application "Adobe Photoshop CS6"'s document 1
activate
set anItem to anItem as string
open file anItem
create selection path item 1
tell application "Adobe Photoshop CS6"
tell current document
set theCropBounds to bounds of selection
crop bounds theCropBounds
end tell
end tell
save OpenedPicture
close OpenedPicture
end tell
end repeat
return input
end run
I've looked in photoshop-cs6-applescript-reference.pdf but as far as i understood i can only set coordinates of the crop.
Any help will be appreciated.
I made the following code to open a website, insert some required text, click "View", and download the resulting document. It runs perfectly if I manually click on it. It also works if I schedule a calendar event to call it when I am sitting in front of my Mac. I have tried every combination of keeping the display on/off and screen unlocked/locked. For some reason, it doesn't seem to work at 5:30am and 2:00pm when I set it to run. I have checked to make sure the disk and Mac are not going to sleep as well. Any thoughts on what I am doing wrong would be greatly appreciated.
--Quit Safari before the program starts
tell application "Safari"
close every window
end tell
--empty "Downloads" folder
tell application "System Events"
delete (every file of folder ("/Users/97pubs/Downloads"))
end tell
--opens DINS website
tell application "Safari"
make new document with properties {URL:"https://www.notams.faa.gov/dinsQueryWeb/"}
activate
ignoring white space
tell front document to repeat until its text contains "About DINS"
end repeat
end ignoring
log "Finished loading"
end tell
delay 2
--Function to press DoD banner on DINS website
to clickClassName(theClassName, elementnum)
tell application "Safari"
do JavaScript "document.getElementsByClassName('" & theClassName & "')[" & elementnum & "].click();" in document 1
end tell
end clickClassName
clickClassName("ui-state-default", 0)
delay 2
--Function to input ICAO abbreviations on the page
to inputByName(theName, num, theValue)
tell application "Safari"
do JavaScript "
document.getElementsByName('" & theName & "')[" & num & "].value ='" & theValue & "';" in document 1
end tell
end inputByName
inputByName("retrieveLocId", 0, "kmaf")
delay 2
--Function to click "View NOTAMs" on page
to clickName(theName, elementnum)
tell application "Safari"
do JavaScript "document.getElementsByName('" & theName & "')[" & elementnum & "].click();" in document 1
end tell
end clickName
--Clicks "View NOTAMs" on page
clickName("submit", 0)
--Waits for next window to completely load before continuing
tell current application
tell application "Safari"
tell window 1
repeat until (exists tab 2)
delay 1
end repeat
ignoring white space
tell front tab to repeat until its text contains "DINS Disclaimer"
end repeat
end ignoring
end tell
end tell
end tell
delay 1
--Clicks "Save all NOTAMs" on page
clickName("button", 1)
delay 2
--Waits for download to complete before continuing
set someFolder to "/Users/path/to/save/location/" -- put your download folder path here
if not (waitForFilesToCopy into someFolder for (10 * minutes)) then
display alert "Error with downloads" message "The downloads did not complete in the time allowed."
if button returned of the result is "Cancel" then error -128
end if
to waitForFilesToCopy into theFolder for timeToWait
(*
waits up to the timeToWait for files to be copied/downloaded to theFolder the test is based on the size of the folder not changing after several seconds the rough timeToWait may need to be adjusted if copying several files/folders parameters - theFolder [mixed]: the folder to check timeToWait [integer]: a maximum timeout value in seconds returns [boolean]: true if copy/download finished, false if timeout
*)
set {theFolder, possible, interval} to {theFolder as text, false, 2} -- change the check interval as desired
tell application "System Events" to set currentSize to size of disk item theFolder -- get initial size
repeat (timeToWait div interval) times -- check every interval seconds
delay interval
tell application "System Events" to set newSize to size of disk item theFolder -- recheck size
if (newSize is equal to currentSize) then
if possible then -- no change since last time
return true -- success
else -- one more time...
set possible to true
end if
else -- update size & possible switch
set {currentSize, possible} to {newSize, false}
end if
end repeat
return false -- fail (timeout)
end waitForFilesToCopy
--Rename PDF to "5 Local NOTAMs.pdf"
tell application "System Events" to set name of file "/Users/path/to/save/location/temp.pdf" to "5 Local NOTAMs.pdf"
--Move NOTAMs to "CrewPapers" folder
tell application "Finder"
move POSIX file "/Users/path/to/save/location/5 Local NOTAMs.pdf" to POSIX file "/Users/path/to/new/location" with replacing
end tell
--Close Safari and Preview windows
tell application "Safari"
close every window
end tell
tell application "Preview"
close every window
end tell
I've encountered a little problem when I wanted to modify a ApplScript, that I am using to get my current iTunes Coverinto a image file that I display on my Desktop via GeekTool.
Now I wanted also to resize this Image because some Images are a bit small...
I found some solutions online, but none of them worked...
And since I am not that much into AppleScript I also can't handle it myself.
This is my current Code:
set the_artwork_file to ((path to home folder) as string) & "Music:iTunes:CurrentArtwork.png"
tell application "System Events"
if ("iTunes" is in name of processes) then
tell application "iTunes"
if (player state is not stopped)
and (player state is not paused)
and (artworks of current track exists)
then
set theArt to front artwork of current track
set pic to (raw data of theArt)
try
set RefNum to (open for access the_artwork_file with write permission)
write (pic) to RefNum
close access RefNum
return
end try
end if
end tell
end if
end tell
do shell script "rm -f " & (POSIX path of the_artwork_file)
Ok, nevermind, I managed to solve it finally.
The Code I generated was basically correct, but I had to put it into an separate Script-File.
In GeekTool I have to call them directly after each other and it works just fine!
This is the Code I used now:
tell application "Image Events"
set this_image to open ((path to home folder) as string) & "Music:iTunes:CurrentArtwork.png"
scale this_image to size 1080
save this_image in ((path to home folder) as string) & "Music:iTunes:CurrentArtwork.png"
close this_image
end tell
I have a simple Applescript to resize photos with Image Events. The photos are all of football players so they are all named by their number as in "1.jpg", "4.jpg" and so on. The issue I run into is when I do multiple batches of players in different directories the script will overwrite a photo with one from another team that has the same filename and was previously done. Again, these photos were all placed in different directories. The end result is after running successfully two or three times the reformatted photos of the players will get confused.
Here's what I have in the script to call Image Events.
on open some_items
repeat with this_item in some_items
try
rescale_and_save(this_item)
end try
end repeat
end open
to rescale_and_save(this_item)
tell application "Image Events"
launch
set the target_width to 290
-- open the image file
set this_image to open this_item
set typ to this_image's file type
copy dimensions of this_image to {current_width, current_height}
if current_width is greater than current_height then
scale this_image to size target_width
else
-- figure out new height
-- y2 = (y1 * x2) / x1
set the new_height to (current_height * target_width) / current_width
scale this_image to size new_height
end if
tell application "Finder" to set new_item to ¬
(container of this_item as string) & "" & (name of this_item)
save this_image in new_item as typ
end tell
end rescale_and_save
You seem to have triggered a bug in Image Events processing multiple items with the same name. I'm not seeing the exact behavior you describe, but I am seeing similar behavior.
I'd suggest you simply tell Image Events to quit after processing each folder; that way it won't get confused. (You don't need the launch, either; the only reason to use launch is if you want a non-background application to open without presenting an untitled document window.)
Incidentally, if you want to overwrite the existing image with the scaled version, all you need is save this_image. Image Events behaves much like any other application if you were to open a document, modify it, and save it.
I have two monitors set up and I am trying to position the window of an application in the second monitor but nothing I do seems to work. For example I am using my laptop and the terminal window is maximized on the screen. Then I plug in an external monitor. I then want to run the applescript and have the terminal maximize on the larger second monitor.
Here is what I have right now:
set monitorTwoPos to {1050, -600}
set monitorTwoSze to {1200, 1920}
tell application "Microsoft Outlook"
set position of window 1 to monitorTwoPos
set size of window 1 to monitorTwoSze
end tell
Here is the error I get:
/Users/vcutten/AppleScripts/SpacesWork.scpt:1291:1332: execution error:
Microsoft Outlook got an error: Can’t make position of window 1 into type specifier. (-1700)
I'm pretty sure I'm just using set position and set size completely wrong :( When I used bounds it kind of works...
Bonus Question:
How can I loop through the open windows and get their size? Thanks!
What have you tried?
I think to solve this you need to calculate the screen size and coordinates of the second monitor. For example, your main monitor starts at position {0,0}. So the starting position of the second monitor has to be something different and you need to find that. Luckily I have written a tool that will give you both the starting coordinates and screen size of your monitors. Once you have the size and position then it's simple. System events can set the size and position of a window so you could do something like this...
set monitorSize to {800, 600}
set monitorPosition to {-800, 0}
tell application "System Events"
tell process "Terminal"
set frontWindow to first window
set position of frontWindow to monitorPosition
set size of frontWindow to monitorSize
end tell
end tell
So from the above script you just need the size and position variables. You can get my tool here called hmscreens which will give you those. You may need to do some adjusting of the coordinates depending on if the screen is measured from the lower left corner or upper left, but that's just simple math.
I hope that helps...
Use bounds instead of position, it works. You can get bounds of the window like this:
tell application "Microsoft Outlook"
get bounds of first window
end tell
Answer to the bonus question:
tell application "Microsoft Outlook"
repeat with nextWindow in (get every window)
get bounds of nextWindow
end repeat
end tell
If you open Replies tab at bottom part of Applescript editor, you will see all get results.
Hope it helps.
Here is a script that handles saving and restoring size and postion for multiple display configurations. It may have some issues with fullscreen apps but it seems to work ok.
-- allSettings is a list of records containing {width:? height:? apps:{{name:? pos:? size:?},...}
-- for each display setup store the apps and their associated position and size
property allSettings : {}
-- create a variable for the current settings
set currentSettings to {}
display dialog "Restore or save window settings?" buttons {"Restore", "Save"} default button "Restore"
set dialogResult to result
tell application "Finder"
-- use the desktop bounds to determine display config
set desktopBounds to bounds of window of desktop
set desktopWidth to item 3 of desktopBounds
set desktopHeight to item 4 of desktopBounds
set desktopResolution to desktopWidth & "x" & desktopHeight
-- find the saved settings for the display config
repeat with i from 1 to (count of allSettings)
if (w of item i of allSettings is desktopWidth) and (h of item i of allSettings is desktopHeight) then
set currentSettings to item i of allSettings
end if
end repeat
if (count of currentSettings) is 0 then
-- add the current display settings to the stored settings
set currentSettings to {w:desktopWidth, h:desktopHeight, apps:{}}
set end of allSettings to currentSettings
--say "creating new config for " & desktopResolution
else
--say "found config for " & desktopResolution
end if
end tell
tell application "System Events"
if (button returned of dialogResult is "Save") then
say "saving"
repeat with p in every process
if background only of p is false then
tell application "System Events" to tell application process (name of p as string)
set appName to name of p
if (count of windows) > 0 then
set appSize to size of window 1
set appPosition to position of window 1
else
set appSize to 0
set appPosition to 0
end if
set appSettings to {}
repeat with i from 1 to (count of apps of currentSettings)
if name of item i of apps of currentSettings is name of p then
set appSettings to item i of apps of currentSettings
end if
end repeat
if (count of appSettings) is 0 then
set appSettings to {name:appName, position:appPosition, size:appSize}
set end of apps of currentSettings to appSettings
else
set position of appSettings to appPosition
set size of appSettings to appSize
end if
end tell
end if
end repeat
end if
if (button returned of dialogResult is "Restore") then
if (count of apps of currentSettings) is 0 then
say "no window settings were found"
else
say "restoring"
repeat with i from 1 to (count of apps of currentSettings)
set appSettings to item i of apps of currentSettings
set appName to (name of appSettings as string)
try
tell application "System Events" to tell application process appName
if (count of windows) > 0 then
set position of window 1 to position of appSettings
set size of window 1 to size of appSettings
end if
end tell
end try
end repeat
end if
end if
end tell
https://gist.github.com/cmackay/5863257