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.
importCode[] := importCode[ First@Cases[NotebookGet@ClipboardNotebook[], Cell[x_, ___] :> x, Infinity]]which will copy whatever is in the clipboard (no checks to see if it is a URL or not), but I don't think this is useful as the chances of you having forgotten and copied something else is high... pasting it as an argument shouldn't be hard and I would prefer explicit over clipboard copy :) – rm -rf Aug 22 '12 at 15:16Shortest[...]would be enough for html parsing instead ofFreeStringQ[...]condition. Maybe something likeStringCases[StringReplace[#,Shortest["<blockquote>"~~__~~"</blockquote>"]:>""],Shortest["<pre><code>"~~("\n"...)~~x__~~("\n"...)~~"</code></pre>"]:>x]. – Silvia Jun 12 '13 at 11:21Shortest, yes, I think they're equivalent and looks cleaner. – rm -rf Jun 12 '13 at 12:01""" -> "\""for handling", feel free to rollback if you don't like it :) . – xzczd Jun 26 '22 at 02:57NotebookWriteinstead ofCellPrintaccording to the discussion in https://mathematica.stackexchange.com/q/269955/1871. Feel free to rollback if you don't like it :) . – xzczd Feb 21 '23 at 06:33