title: Match neighbour tag by Class values
body: <p>I have to create dictinary for class values from input HTML.</p>
  
  <p><strong>Input</strong>:</p>
  
  <pre><code>  &lt;div&gt;
       &lt;p id="quarter-line-below1" class="firstpara-rw"&gt;&lt;span class="dropcap-image-rw print-exclude-rw"&gt;&lt;img alt="2014" src="243864_20.png"/&gt;&lt;/span&gt;&lt;span class="dropcap-rw"&gt;2014 &lt;/span&gt;has had some .............&lt;/p&gt;
       &lt;p id="firstpara1" class="firstpara-rw"&gt;&lt;span class="dropcap-image-rw print-exclude-rw"&gt;&lt;img alt="O" src="243864_69.png"/&gt;&lt;/span&gt;&lt;span class="dropcap-rw"&gt;O&lt;/span&gt;f course ...........&lt;/p&gt;
       &lt;p class="test1-image-rw print-exclude-rw" id="ornament1-orn"&gt;&lt;img src="243865_18.png" /&gt;&lt;/p&gt;
       &lt;p class="test1-rw" id="ornament1"&gt;aA bB cC dD eE fF gG hH iI&lt;/p&gt;
       &lt;p class="test2-image-rw print-exclude-rw" id="ornament1-orn"&gt;&lt;img src="243865_18.png" /&gt;&lt;/p&gt;
       &lt;p class="test22-rw" id="ornament1"&gt;aA bB cC dD eE fF gG hH iI&lt;/p&gt;
   &lt;/div&gt;
  </code></pre>
  
  <p><strong>My Algo is</strong>:</p>
  
  <ol>
  <li>Parse content by <code>LXML</code>.</li>
  <li>Get all tags which class value contains <code>-image-rw</code> by <code>xpath</code></li>
  <li>Iterate on every tag from the step2.</li>
  <li>Get Target class value which contains <code>-image-rw</code> and its respective value means remove <code>-image</code> from class value.</li>
  <li>Get next tag of target tag.</li>
  <li>Check target value is present in the net tag or not.</li>
  <li>If present then add to dictionary.</li>
  </ol>
  
  <p><strong>Code</strong>:</p>
  
  <pre><code>import lxml.html as PARSER
  import time
  
  start_time = time.time()
  root = PARSER.fromstring(content)
  target_tags = root.xpath("//*[contains(@class, '-image-rw')]")
  valid_class = {}
  #- Validation.
  for i in target_tags:
      target_class = [j.strip() for j in  i.attrib["class"].split() if "-image-rw" in j][0].strip()
      target_class_next = target_class.replace("-image-rw", "-rw")
      try:
         for j in i.getnext().attrib["class"].split():
             print j
             if j.strip()==target_class_next:
                 valid_class[target_class] = target_class_next
                 break
      except KeyError:
          print "Class value missing. ", i
  
  print "Time:-", time.time() - start_time
  print "Result:-", valid_class
  </code></pre>
  
  <p><strong>Output</strong>:</p>
  
  <pre><code>Time:- 0.000622987747192
  Result:- {'test1-image-rw': 'test1-rw', 'dropcap-image-rw': 'dropcap-rw'}
  </code></pre>
  
  <p><strong>Is any other Pythonic and Optimized way to get above result?</strong> </p>