Are there any browser addons, user scripts, SEDE magic, etc. to download code blocks from Stack Exchange posts?

Background use case: I'm working on a collection of test cases for the LaTeX beamer class and thought that I could use the code from the answers I have written on this topic in the past couple of years. However, as these are 2000+ posts, I don't particular fancy copy&pasting all of them. Visiting each post once and pressing some button to download a file would be OK. Something automatic would of course be better.

I'm aware of Shortcut or button for copying posted code from Stack Overflow and How to easily copy, download, or view all of "code box" in question? -- however the answers there seem to focus on copying the code block, an extra step I would like to avoid.


This query should give you your first code blocks in all your posts.

This works because the body of the Posts table will have the final HTML that you'll also see on a Q/A page. A code block starts with the tags <pre><code> and ends with </code></pre>. By using the CHARINDEX we can find the positions of those tags and then use SUBSTRING to project the data we need.

If you need all code blocks this query with a recursive CTE works and is based on the same approach.

select id 
     , substring(body,[start code], [end code] - [start code]) [first code block]
select id
     , body
     , charindex(N'<pre><code>', body) + 11 [start code]
     , charindex(N'</code></pre>', body) [end code]
from posts
where owneruserid = 36296
) data
where [end code]>0

When run today this is what it looks like:

enter image description here

Notice you can download this result as CSV and then post process with tooling you're familiar with.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .