Screenshot Script - Help Appreciated!

Hey there,

Thanks for any help your’e able to offer - I’m new to Applescript and am quite keen to learn the ropes!

Basically, I’m trying to create a script that will open websites, take screenshots, and save in an organized file directory (under site name, page name, date, etc).

I’m early stages yet - with all functionality not done, but I have run into an issue that I’m unable to fix myself.

What I think the error is
I’m setting siteName & pageName as paragraphs in a TextEdit doc. I think it is taking the linebreak from these, so it tries to save the file as: siteName [LINEBREAK] pageName [LINEBREAK] .jpg. I think the linebreaks are meaning it doesn’t save correctly, as it simply just saves as siteName.

Any tips?

--Variables
set whichUrl to 1
set siteID to 2
set nameUrl to 3

--Set path and create directory structure
tell application "Finder"
	set picPath to ((POSIX path of (path to desktop)) & "TestScript/") as string
	if not (exists folder picPath) then
		do shell script "mkdir -p " & picPath
	end if
end tell

--Get Number of URLs
tell application "TextEdit"
	set theCount to the count of paragraphs of front document
end tell

--Repeat this for every URL
repeat theCount / 3 times
	
	--Get the next URL
	tell application "TextEdit"
		set currentUrl to paragraph whichUrl of front document as text
		set siteName to paragraph siteID of front document as text
		set pageName to paragraph nameUrl of front document as text
	end tell
	
	--Open the URL in Safari
	tell application "Safari"
		activate
		set the URL of document 1 to currentUrl
		
		--Wait until it loads, then take a screenshot
		delay 5
		set picName to (siteName & "-" & pageName & ".jpg") as string
		do shell script "screencapture -tjpg " & quoted form of (picPath & picName)
	end tell
	
	--Increase the counter for next time
	set whichUrl to whichUrl + 3
	set siteID to siteID + 3
	set nameUrl to nameUrl + 3
end repeat

Hello Brendan and welcome to MacScripter’s ! :slight_smile:

I have made a quick fix for you. There are a phletora of ways to do this, I just did what was simplest. You may want to look into text item delimiters for removing unwanted characters.

I also changed your variables for indexing the paragraphs into properties, as those variables, are more like consts, if you haven’t got more lines in your file, that is.

--Get the next URL
property whichUrl : 1
property siteID : 2
property nameUrl : 3

tell application "TextEdit" to tell its front document
	set currentUrl to text 1 thru -2 of (paragraph whichUrl as text)
	set siteName to text 1 thru -2 of (paragraph siteID as text)
	set pageName to text 1 thru -2 of (paragraph nameUrl as text)
end tell

You may really want to find a trim handler for removing any unwanted spaces in both ends.

Happy Scripting.

Thanks for the help - really appreciate it!
I edited those bits in to mine, and it worked once - but trying to run it again, I get an error
“TextEdit got an error: Can’t get paragraph 10 of document 1. Invalid index.” number -1719 from paragraph 10 of document 1"

Really appreciate the time you’ve taken to give a hand!

--Variables
property whichUrl : 1
property siteID : 2
property nameUrl : 3

--Set path and create directory structure
tell application "Finder"
	set picPath to ((POSIX path of (path to desktop)) & "TestScript/") as string
	if not (exists folder picPath) then
		do shell script "mkdir -p " & picPath
	end if
end tell

--Get Number of URLs
tell application "TextEdit"
	set theCount to the count of paragraphs of front document
end tell

--Repeat this for every URL
repeat theCount / 3 times
	
	--Get the next URL
	tell application "TextEdit" to tell its front document
		set currentUrl to text 1 thru -2 of (paragraph whichUrl as text)
		set siteName to text 1 thru -2 of (paragraph siteID as text)
		set pageName to text 1 thru -2 of (paragraph nameUrl as text)
	end tell
	
	--Open the URL in Safari
	tell application "Safari"
		activate
		set the URL of document 1 to currentUrl
		
		--Wait until it loads, then take a screenshot
		delay 5
		set picName to (siteName & "-" & pageName & ".jpg") as string
		do shell script "screencapture -tjpg " & quoted form of (picPath & picName)
	end tell
	
	--Increase the counter for next time
	set whichUrl to whichUrl + 3
	set siteID to siteID + 3
	set nameUrl to nameUrl + 3
end repeat

Hi Brendan.

You’re absolutely right about what the problem is. When you pull a ‘paragraph’ directly from a TextEdit document, it ends with whatever the paragraph delimiter (what you call a LINEBREAK) is in the text at that point.

McUsrII’s suggestion gets each paragraph in turn from TextExit and sets the relevant variable to the result stripped of its last character, which is assumed to be the paragraph separator. This is fine as long as none of the paragraphs is empty (which it probably won’t be in your case) and as long as there is indeed a paragraph separator at the end of the last paragraph (which is far less certain).

Another easy way to handle the problem is extract the text in its entirety ” so that you’re dealing with text in AppleScript rather than in a TextEdit document ” and then extract the paragraphs. In AppleScript text, ‘paragraphs’ do NOT contain the paragraph separators:

--Get the next URL
property whichUrl : 1
property siteID : 2
property nameUrl : 3

tell application "TextEdit" to set txt to text of its front document

set currentUrl to paragraph whichUrl of txt
set siteName to paragraph siteID of txt
set pageName to paragraph nameUrl of txt

Paragraphs, of course, are whatever’s delimited by paragraph delimiters. An empty line between two paragraphs of text is a paragraph in its own right and has to be included in the numbering.

Thanks for the help - really appreciate it!
I’ve made some edits to my code:

It reads the data from the open TextEdit doc (Can I make this read it from a saved document?) and then loads each site, takes a screenshot, and saves it under the site name, a datestamped folder, with a descriptive filename.

One issue I note is that “Activate” isn’t bringing Safari to the front - any clues on why not?
Am I likely to have any issues transitioning this from saving to my desktop, to saving to an AFP server (i.e. afp//server-name/folder/)?


--Generate datestamp--
on dateStamp()
	tell (current date) to return text 3 thru 8 of (year * 10000 + (its month as integer) * 100 + day as string)
end dateStamp
set dateStamp to dateStamp()
--end datestamp--

--Set Variables--
property whichUrl : 1
property siteID : 2
property nameUrl : 3
--end variables--


--Get number of sites and repeat for that number--
tell application "TextEdit"
	set theCount to the count of paragraphs of front document
end tell
repeat theCount / 3 times
	--end number of sites--
	
	
	--Set instance specific variables--
	tell application "TextEdit" to set txt to text of its front document
	
	set currentUrl to paragraph whichUrl of txt
	set siteName to paragraph siteID of txt
	set pageName to paragraph nameUrl of txt
	--end instance specific variables--
	
	--Set path and create directory structure--
	tell application "Finder"
		set picPath to ((POSIX path of (path to desktop)) & "TestScript/" & siteName & "/" & dateStamp & "/") as string
		if not (exists folder picPath) then
			do shell script "mkdir -p " & picPath
		end if
	end tell
	--end set path and directory structure--
	
	--Open URL in Safari--
	tell application "Safari"
		activate
		set the URL of document 1 to currentUrl
		--end open URL--
		
		--Delay, then screenshot--		
		delay 5
		set picName to (dateStamp & " " & siteName & " " & pageName & ".jpg") as string
		do shell script "screencapture -tjpg " & quoted form of (picPath & picName)
	end tell
	--end delay and screenshot--
	
	--Set variables for next run--
	set whichUrl to whichUrl + 3
	set siteID to siteID + 3
	set nameUrl to nameUrl + 3
	--end set variables for next run--
end repeat

Hi,

Here’s an example parsing the text:

tell application "TextEdit"
	make new document at front with properties {text:"1
2
3
4
5
6
7
8
9
"}
	set t to text of front document
end tell
set p to paragraphs of t
set c to (count p) div 3
set r to {}
repeat with i from 0 to c - 1
	set n to i * 3
	tell p
		set {x, y, z} to {item (n + 1), item (n + 2), item (n + 3)}
	end tell
	set end of r to {x, y, z}
end repeat
return r

Edited: darn, this errors if there is less than 3 paragraphs. Need to change something.

Had a hard time connecting

Me too. (Hard time connecting.)

Anyways, I dug up and old trim handler I had, and brushed some deprecation of it, and incorporated it, because it is annoying at times, when a space sneaks in at the end at the front or end of such lines.

I know it doesn’t happen to anybody but me but . :slight_smile:

And I know I could have made the trim handler a little bit smarter/shorter, but I have to head back into something.

--Set Variables--
property whichUrl : 1
property siteID : 2
property nameUrl : 3
--end variables--

--Generate datestamp--
on dateStamp()
	tell (current date) to return text 3 thru 8 of (year * 10000 + (its month as integer) * 100 + day as string)
end dateStamp
on trim(R)
	-- R { stringToStrip:_str, charlistToRemoveAsNumbers:_char}
	--set _whites to {32, 9, 13, 10}
	local _strBuf
	copy (stringToStrip of R) to _strBuf
	set _strBuf to _strBuf as string
	if (charlistToRemoveAsNumbers of R) contains (id of (character 1 of _strBuf)) then
		repeat until (charlistToRemoveAsNumbers of R) does not contain (id of (character 1 of _strBuf))
			try
				set _strBuf to ((characters 2 thru ((length of _strBuf) as integer) of _strBuf) as string)
			on error
				set _strBuf to ""
				return _strBuf
			end try
		end repeat
	end if
	if (charlistToRemoveAsNumbers of R) contains (id of (character (length of _strBuf) of _strBuf)) then
		repeat until not (R's charlistToRemoveAsNumbers contains (id of (character (length of _strBuf) of _strBuf)))
			set _strBuf to ((characters 1 thru (((length of _strBuf) as integer) - 1) of _strBuf) as string)
		end repeat
	end if
	return _strBuf
end trim

on run
	
	set dateStamp to dateStamp()
	--end datestamp--
	
	
	
	--Get number of sites and repeat for that number--
	tell application "TextEdit" to tell its front document
		set theCount to the count of paragraphs
		set txt to text of it
	end tell
	repeat theCount / 3 times
		--end number of sites--
		
		
		--Set instance specific variables--
		
		set currentUrl to trim({stringToStrip:(paragraph whichUrl of txt), charlistToRemoveAsNumbers:{32, 9, 13, 10}})
		set siteName to trim({stringToStrip:(paragraph siteID of txt), charlistToRemoveAsNumbers:{32, 9, 13, 10}})
		set pageName to trim({stringToStrip:(paragraph nameUrl of txt), charlistToRemoveAsNumbers:{32, 9, 13, 10}})
		--end instance specific variables--
		
		--Set path and create directory structure--
		tell application "Finder"
			set picPath to ((POSIX path of (path to desktop)) & "TestScript/" & siteName & "/" & dateStamp & "/") as string
			if not (exists folder picPath) then
				do shell script "mkdir -p " & picPath
			end if
		end tell
		--end set path and directory structure--
		
		--Open URL in Safari--
		tell application "Safari"
			activate
			set the URL of document 1 to currentUrl
			--end open URL--
			
			--Delay, then screenshot--		
			delay 5
			set picName to (dateStamp & " " & siteName & " " & pageName & ".jpg") as string
			do shell script "screencapture -tjpg " & quoted form of (picPath & picName)
		end tell
		--end delay and screenshot--
		
		--Set variables for next run--
		set whichUrl to whichUrl + 3
		set siteID to siteID + 3
		set nameUrl to nameUrl + 3
		--end set variables for next run--
	end repeat
	
end run

‘activate’ is broken. You can:

tell app “SomeApp”
launch
activate
end tell

This will work when TextEdit is not running from the start.

Edited: I’m actually saying that it doesn’t work with some apps. Guess it’s up to the app or something. :slight_smile:

gl,
kel

Things change.

I’ll take your word for it, and use that pattern from now on. It is just one word, that may be superfluous one some versions, but it is better to have it, or them, work on every version. :slight_smile:

Thanks kel.

Just for prosperity:

Hi McUsr,

Unless you’re in a System Events process tell block, launch and activate is ok. Otherwise I use the shorter way. e.g.

-- launch unhidden and frontmost
tell application "TextEdit"
	launch
	activate
end tell
delay 2
-- bring something else frontmost
tell application "Finder" to activate
delay 2
tell application "System Events"
	tell process "TextEdit"
		set frontmost to true
	end tell
end tell

Is there a way to tell TextEdit to open a file at location x://folder/file.txt type thing?

Basically, at current - my script requires TextEdit to be open, and if Safari is already open - it needs to be near the foreground. I’d like to eventually package this as an application - so it can be clicked on, launch all it’s dependencies, get screenshotting and be done.

On that note - is there a way to make it screenshot just the active window? (Or make Safari full screen?)

Seriously appreciate this help!

Hi brendanhad,

If you want to see how a Applescript reference might look, then run this and look at the result:

set the_file to choose file

result: alias “Macintosh HD:Users:kelhome:Desktop:ExFrontmost.scpt”

if you want to open a file, then use a reference:

set the_file to choose file
tell application "TextEdit"
	launch
	activate
	open the_file
end tell

Thanks Kel! Huge help.
I now have it opening the correct TextEdit file & Safari - loading all the sites, screenshotting them and saving off an in organized file structure. I now just need to see if I can improve the screenshotting (screenshot active window only, or make safari full-screen) - I’ll be pretty much done.

Amazed at how helpful AppleScript can be… Wondering what else I can automate!

Hi brendanhad,

Yeah, it is powerful. You should get the AppleScriptLanguageGuide.pdf. There are more than one type of reference instead of the alias reference.

gl,
kel

This is from the AppleScriptLanguageGuide.pdf:

Man, how do you copy from pdf

gl,
kel

So close to being complete!
I’ve ported it over to Chrome, and it full-screens chrome to take the screenshot - meaning no cropping necessary.

This part of the code is not working though:

--Set path and create directory structure--
tell application "Finder"
	set screenPath to alias "Folder:Folder Data:Clients Folder:Client 2013:General:Folder Name:Folder:Folder Name:Screenshots:"
	set picPath to (screenPath & "TestScript/") as string
	if not (exists folder picPath) then
		do shell script "mkdir -p " & picPath
	end if
end tell
--end set path and directory structure--

(I’ve changed file names for security)

I think the issue is that there’s spaces in the folder address, as it spits out six or seven “mkdir permissions failed” errors, one for each bit between each space.

How can I correctly reference this URL?
(I use the same URL for reading the text file - it works fine)

I don’t have write access to the root folder, but do to the folder I wish to write to…

Thanks again for all your help!

You are so close brendanhad.

Why do you tease, haha!

the Finder expects HFS paths (colon separated), the shell needs always POSIX paths (slash separated).


.
 set picPath to (screenPath & "TestScript:") as string
   if not (exists folder picPath) then
       do shell script "mkdir -p " & quoted form of POSIX path of picPath
   end if
.

One more thing. To change a appleScript path reference to posix path for do shell script", here’s an example

set f to choose file
set posix_path to POSIX path of f
do shell script "echo " & posix_path