0

I am using Python element tree to parse xml file

lets say i have an xml file like this ..

<html>
<head>
    <title>Example page</title>
</head>
<body>
    <p>hello this is first paragraph </p>
    <p> hello this is second paragraph</p>
</body>
</html>

is there any way i can extract the body with the p tags intact like

desired= "<p>hello this is first paragraph </p> <p> hello this is second paragraph</p>"

3 Answers 3

1

The following code does the trick.

import xml.etree.ElementTree as ET

root = ET.fromstring(doc)  # doc is a string containing the example file
body = root.find('body')
desired = ' '.join([ET.tostring(c).strip() for c in body.getchildren()])

Now:

>>> desired
'<p>hello this is first paragraph </p> <p> hello this is second paragraph</p>'
Sign up to request clarification or add additional context in comments.

2 Comments

also its not just p tags there can be any like <b> tags <i> tags any suggestions ...
That will pull out any of the body's children, regardless of the tag type. I think it may be confusing that I used p in my code. That has nothing to do with the <p> tag, and I will change the code to be clear. This solution will not work, however, when the body has text that is not inside a child element.
0

You can use lxml library, lxml

So, this code will help you.

import lxml.html

htmltree = lxml.html.parse('''
<html>
<head>
<title>Example page</title>
</head>
 <body>
<p>hello this is first paragraph </p>
<p> hello this is second paragraph</p>
</body>
</html>''')
p_tags = htmltree.xpath('//p')
p_content = [p.text_content() for p in p_tags]

print p_content

Comments

0

A slightly different way to @DavidAlber, where the children could easily be selected:

from xml.etree import ElementTree

tree = ElementTree.parse("example.xml")
body = tree.findall("/body/p")

result = []
for elem in body:
     result.append(ElementTree.tostring(elem).strip())

print " ".join(result)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.