March 8, 2011 at 7:54 AM by Dr. Drang
I signed up for Amazon’s Associates program a few months ago. I figured if anyone ever buys something (pens, for example) based on my recommendation, I might as well get a little something, you know, for the effort.
Amazon thinks it’s helping its associates out by providing a popup “window” that has one-click access to a variety of link types.
You can get premade HTML for
- A text and image link
- An image-only link
- A text-only link
Unfortunately, I don’t like any of these options. Because I write my posts in Markdown, I don’t want HTML; all I want is the URL of the associate link. Until today, I’d been selecting the URL out of the text-only link, copying it to the clipboard, and then switching to TextMate to paste it into my blog post. Those days are over.
I noticed that all my associate URLs have the same structure,
<itemID> string is unique to the item, the
<associateID> is unique to me, and the
<moredigits> come from I-have-no-idea-but-they-never-change-for-me.
The rigid structure of the URL makes it easy to generate automatically. I just create a TextExpander snippet with AppleScript content that looks like this:
1: tell application "Safari" to set theURL to the URL of the front document 2: 3: set cmd to "echo '" & theURL & ¬ 4: "' | perl -pe 's#.*/dp/([^/]+)/.*#$1#'" 5: set itemID to do shell script cmd 6: 7: set aLink to ¬ 8: "http://www.amazon.com/gp/product/" & itemID ¬ 9: & "?ie=UTF8&tag=<associateID>&linkCode=as2&camp=<digits>&creative=<moredigits>&creativeASIN=" ¬ 10: & itemID
Line 1 gets the URL of the frontmost Safari page, which is assumed to have the item I want to link to. This URL is not a associate URL, but it does contain the item ID in a section that looks like
/dp/<itemID>/. Lines 3-5 use a Perl regular expression to extract the item ID from that URL.1 Lines 7-10 then construct the associate URL.
Any time I need the associate URL, I just type the snippet’s abbreviation,
;amazon, and TextExpander generates it for me. Very convenient.
If you’re an Amazon Associate and want to use this snippet, just change the
<moredigits> parts in Line 9 to whatever Amazon uses for you.
And just after I sign up as an Associate, Amazon pulls the plug in Illinois to avoid sales taxes. Figures.
The regex isn’t particularly complicated, but it does use a feature of Perl you may not have seen before. Perl’s substitute command, which usually looks like
s/original/replacement/, doesn’t have to use slash delimiters. In fact, if you’re going to have slashes in the
replacmentstrings, it’s better not to use slash delimiters so you don’t have to escape them. Perl lets you use almost any character as the delimiter; I chose the hash because it wasn’t in either the
replacementpart of my regex. ↩