title: How can I escape *all* characters into their corresponding html entity names and numbers in Python?
body: <p>I wanted to encode a string to its corresponding html entities but unfortunately I am not able to. As I said in question title, I want <em>all</em> characters in a string to be converted into their corresponding html entity(both numbers and names). So according to the <a href="https://docs.python.org/3/library/html.html" rel="nofollow noreferrer">documentation</a>. I tried:</p>
  
  <pre><code>In [31]: import html
  
  In [32]: s = '&lt;img src=x onerror="javascript:alert("XSS")"&gt;'
  
  In [33]: html.escape(s)
  Out[33]: '&amp;lt;img src=x onerror=&amp;quot;javascript:alert(&amp;quot;XSS&amp;quot;)&amp;quot;&amp;gt;'
  </code></pre>
  
  <p>But I want all characters to be converted and not just '&lt;' , '>', '&amp;' ,etc.
  And also <code>html.escape</code> only gives html entity <em>names</em> and not numbers but I want both.</p>
  
  <p>But surprisingly <a href="https://docs.python.org/3/library/html.html#html.unescape" rel="nofollow noreferrer"><code>html.unescape</code></a> unescapes all entities into their corresponding characters.</p>
  
  <pre><code>In [34]: a = '&lt;img src=x onerror="&amp;#0000106&amp;#0000097&amp;#0000118&amp;#0000097&amp;#0000115&amp;#0000099&amp;#0000114&amp;#0000105&amp;#0000112&amp;#0000116&amp;#000005
      ...: 8&amp;#0000097&amp;#0000108&amp;#0000101&amp;#0000114&amp;#0000116&amp;#0000040&amp;#0000039&amp;#0000088&amp;#0000083&amp;#0000083&amp;#0000039&amp;#0000041"&gt;'
  
  In [35]: html.unescape(a)
  Out[35]: '&lt;img src=x onerror="javascript:alert(\'XSS\')"&gt;' 
  </code></pre>
  
  <p>So can I do the same with <a href="https://docs.python.org/3/library/html.html#html.escape" rel="nofollow noreferrer"><code>html.escape</code></a>?</p>
  
  <p>I am really surprised why <em>all</em> resources on internet for encoding and decoding html entities are not encoding all chars and also the php <code>htmlspecialchars()</code> function don't do that. And I don't want to write all html entity numbers from <a href="https://www.freeformatter.com/html-entities.html" rel="nofollow noreferrer">here</a> character by character.</p>