Make Bleach to allow code tags
<p>I'm trying to use <a href="https://github.com/mozilla/bleach" rel="nofollow">bleach</a> to escape HTML tags. It works just fine, unless I'm trying to insert a code snipped as a content of a page. The snippet is inserted like this:</p>

<pre><code>&lt;pre&gt;
&lt;code&gt;
 Code sample
&lt;/code&gt;
&lt;/pre&gt;
</code></pre>

<p>The code sample may contain html tags. How can I make bleach not to escape tags if they are inside <code>&lt;pre&gt;&lt;code&gt;</code>? I know I can whitelist some tags, but it seems that there is not way to whitelist all tags if they are inside the code block and blacklist then in other cases. The outer html markup is produced from Markdown.</p>

<p>Moreover, bleach escapes all &lt; and > signs, but if they occur in the code snippet, it looks like this:</p>

<pre><code>for (auto a = 0; i &amp;lt; 10; ++i)
</code></pre>

<p>If bleach is not capable of this, could you advice another escaper, that can do what I need?</p>

<p>You want to whitelist children tags of &lt; pre > and &lt; code >. From what I can infer from reading on the documentation, you have to define one by one the tags you want to whitelist or use a callable that every time a tag gets encountered the callable will be invoked.</p>

<p>Check on the documentation the section named: <a href="https://bleach.readthedocs.io/en/latest/clean.html#callable-filters" rel="nofollow">Callable Filters</a></p>

<p>A possible solution for your problem is to pass a function on the clean bleach.clean that will check whether the tag encountered by then clean method is a child of the code html tag. You will have to parse the HTML there, you can use HTML parser for that along with <a href="https://docs.python.org/2/library/xml.etree.elementtree.html#treebuilder-objects" rel="nofollow">TreeBuilder</a> of <code>xml.eTree</code> package</p>

<p>Here is an <a href="http://stackoverflow.com/questions/13334044/get-the-html-under-a-tag-using-htmlparser-python">example</a> on a different answer.</p>

python markdown bleach