title: HTML to Word docx
body: <p>I have some HTML formatted text I've got with <code>BeautifulSoup</code>. I'd like to convert all <em>italic</em> (tag i), <strong>bold</strong> (b) and links (a href) to Word format via <code>docx</code> run command.</p>
  
  <p>I can make a paragraph:</p>
  
  <pre><code>p = document.add_paragraph('text')
  </code></pre>
  
  <p>I can ADD next sequence as bold/italic:</p>
  
  <pre><code>p.add_run('bold').bold = True
  p.add_run('italic.').italic = True
  </code></pre>
  
  <p>Intuitively, I could find all particular tags (ie. <code>soup.find_all('i')</code>) and then watch indices and then concatenate partial strings...</p>
  
  <p>...but maybe there's a better, more elegant way?</p>
  
  <p>I don't want libraries or solutions that just convert a html page to word and save them. I want a little more control.</p>
  
  <p>I got nowhere with a dictionary. Here is the code and visual wrong (from code) and right (desired) result:</p>
  
  <pre><code>from docx import Document
  import os
  from bs4 import BeautifulSoup
  
  html = '&lt;a href="http://someurl.you"&gt;hi, I am link&lt;/a&gt; this is some nice regular text. &lt;i&gt; oooh, but I am italic&lt;/i&gt; ' \
          ' or I can be &lt;b&gt;bold&lt;/b&gt; '\
          ' or even &lt;i&gt;&lt;b&gt;bold and italic&lt;/b&gt;&lt;/i&gt;'
  
  def get_tags(text):
      soup = BeautifulSoup(text, "html.parser")
      tags = {}
      tags["i"] = soup.find_all("i")
      tags["b"] = soup.find_all("b")
  
      return tags
  
  
  def make_test_word():
      document = Document()
  
      document.add_heading('Demo HTML', 0)
  
      soup = BeautifulSoup(html, "html.parser")
  
      p = document.add_paragraph(html)
  
      # p.add_run('bold').bold = True
      # p.add_run(' and some ')
      # p.add_run('italic.').italic = True
  
      file_name="demo_html.docx"
      document.save(file_name)
      os.startfile(file_name)
  
  
  make_test_word()
  </code></pre>
  
  <p><a href="https://i.stack.imgur.com/UM74G.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/UM74G.jpg" alt="enter image description here"></a></p>