Code extractor using the StackExchange API
The following code uses the 2.0 version of the SE API and has also been cleaned up a bit (place it in your kernel's init.m
or your custom functions package if you'd like to be able to use it anytime).
The function takes a single string argument, which is the URL obtained from the share link under a question/answer.
Example
importCode[url_String] :=
With[{
filterCode = StringCases[#, ("<pre><code>" ~~ ("\n" ...) ~~ x__ ~~ ("\n" ...) ~~
"</code></pre>") /; StringFreeQ[x, "<pre><code>" | "</code></pre>"] :> x] &,
convertEntities = StringReplace[#,
{">" -> ">", "<" -> "<", "&" -> "&", """ -> "\""}] &,
makeCodeCell = Scan[NotebookWrite[EvaluationNotebook[],
Cell[Defer@#, "Input", CellTags -> "Ignore"]] &, Flatten@{#}] &,
postInfo = Import[ToString@
StringForm["http://api.stackexchange.com/2.1/posts/`1`?site=`2`&filter=!9hnGsretg",
#3, #1] & @@ {First@StringCases[#, Shortest[s__] ~~ "." ~~ ___ :> s], #2, #3} & @@
StringSplit[StringDrop[url, 7], "/"][[;; 3]], "JSON"]},
OptionValue["items" /. postInfo, "body"] // filterCode // convertEntities //
makeCodeCell]
NOTE: I don't do any rigorous error checking or check to see if you're entering a valid Stack Exchange URL or if the question/answer is deleted (deleted posts cannot be accessed via the API), etc. So if you get any errors, it might be worthwhile to check if there's something wrong on the site.
Also, SE API limits you to 300 calls/day/IP, if I remember correctly. That's quite a lot of calls for any reasonable person and ideally, you shouldn't cross that. Nevertheless, a possibility of being throttled is something to keep in mind if you also happen to be playing with the API for other purposes such as site statistics, etc.