I'm trying to change certain "p" tags to "span" tags and to append a
"br" at the end of the outer span. I've been thrashing about for
awhile, going through the BeautifulSoup documentation, the unit tests
and scanning the source code, and the following is as far as I've
gotten. My questions:
1) How do I get the "br" tag to appear AFTER the outer span?
2) Am I approaching this problem correctly or is there a more elegant
way to do this?
3) Optional bonus question -- should I just be combining the spans
somehow, and is there a good way to do that?
Thanks for any help...
Here's the example:
from BeautifulSoup import BeautifulSoup, Tag
soup = BeautifulSoup("""
<html>
<body>
<p class="c1">
<span class="c5">
1 // Values.scala
</span>
</p>
<p class="c1">
<span class="c5">
2
</span>
</p>
<p class="c1">
<span class="c5">
3 val anInteger: Int = 11
</span>
</p>
<p class="c1">
<span class="c5">
4 val aDouble: Double = 1.4
</span>
</p>
<p class="c1">
<span class="c5">
5 // true or false:
</span>
</p>
<p class="c1">
<span class="c5">
6 val trueOrFalse: Boolean = true
</span>
</p>
</body>
</html>
""")
for e in soup.findAll("p", { "class" : "c1" }):
print e; print
br = Tag(soup, "br")
span = Tag(soup, "span", [("class", "c1")])
span.insert(0, e.renderContents())
span.append(br)
print span
e.replaceWith(span)
print "***"
print(soup)
------------------------------------- And here's the output:
------------------------------------------
<p class="c1">
<span class="c5">
1 // Values.scala
</span>
</p>
<span class="c1">
<span class="c5">
1 // Values.scala
</span>
<br /></span>
***
<p class="c1">
<span class="c5">
2
</span>
</p>
<span class="c1">
<span class="c5">
2
</span>
<br /></span>
***
<p class="c1">
<span class="c5">
3 val anInteger: Int = 11
</span>
</p>
<span class="c1">
<span class="c5">
3 val anInteger: Int = 11
</span>
<br /></span>
***
<p class="c1">
<span class="c5">
4 val aDouble: Double = 1.4
</span>
</p>
<span class="c1">
<span class="c5">
4 val aDouble: Double = 1.4
</span>
<br /></span>
***
<p class="c1">
<span class="c5">
5 // true or false:
</span>
</p>
<span class="c1">
<span class="c5">
5 // true or false:
</span>
<br /></span>
***
<p class="c1">
<span class="c5">
6 val trueOrFalse: Boolean = true
</span>
</p>
<span class="c1">
<span class="c5">
6 val trueOrFalse: Boolean = true
</span>
<br /></span>
***
<html>
<body>
<span class="c1">
<span class="c5">
1 // Values.scala
</span>
<br /></span>
<span class="c1">
<span class="c5">
2
</span>
<br /></span>
<span class="c1">
<span class="c5">
3 val anInteger: Int = 11
</span>
<br /></span>
<span class="c1">
<span class="c5">
4 val aDouble: Double = 1.4
</span>
<br /></span>
<span class="c1">
<span class="c5">
5 // true or false:
</span>
<br /></span>
<span class="c1">
<span class="c5">
6 val trueOrFalse: Boolean = true
</span>
<br /></span>
</body>
</html>