Jurudocs
Jurudocs

Reputation: 9175

BeautifulSoup/LXML.html: delete tag and its children if child looks like x

I have a problem getting to the right solution. I want to delete <question> and its children if <answer> is = 99. As a result, I need a string with the filtered questions. I have the following html structure:

<html>
 <body>        
  <questionaire>
   <question>
    <questiontext>
     Do I have a question?
    </questiontext>
    <answer>
     99
    </answer>
   </question>
   <question>
    <questiontext>
     Do I love HTML/XML parsing?
    </questiontext>
    <questalter>
     <choice>
      1 oh god yeah
     </choice>
     <choice>
      2 that makes me feel good
     </choice>
     <choice>
      3 oh hmm noo
     </choice>
     <choice>
      4 totally
     </choice>
     </questalter>
     <answer>
      4
    </answer>
   </question>
   <question>
  </questionaire>
 </body>
</html>      

So far i tried to realize it with xpath...but lxml.html has no iterparse...has it? Thanx!

Upvotes: 0

Views: 917

Answers (2)

Matt Williamson
Matt Williamson

Reputation: 40223

This will do exactly what you need:

from xml.dom import minidom

doc = minidom.parseString(text)
for question in doc.getElementsByTagName('question'):
    for answer in question.getElementsByTagName('answer'):
        if answer.childNodes[0].nodeValue.strip() == '99':
            question.parentNode.removeChild(question)

print doc.toxml()

Result:

<html>
 <body>        
  <questionaire>

   <question>
    <questiontext>
     Do I love HTML/XML parsing?
    </questiontext>
    <questalter>
     <choice>
      1 oh god yeah
     </choice>
     <choice>
      2 that makes me feel good
     </choice>
     <choice>
      3 oh hmm noo
     </choice>
     <choice>
      4 totally
     </choice>
     </questalter>
     <answer>
      4
    </answer>
   </question>
  </questionaire>
 </body>
</html>

Upvotes: 1

Sean McCully
Sean McCully

Reputation: 1132

from lxml import etree
html = etree.fromstring(html_string)
questions = html.xpath('/html/body/questionaire/question')
for question in questions:
    for elements in question.getchildren():
        if element.tag == 'answer' and '99' in element.text:
            html.xpath('/html/body/questionaire')[0].remove(question)
print etree.tostring(html)

Upvotes: 1

Related Questions