python - Building paragraph tag in beautifulsoup -
i want add paragraph soup. paragraph should -
<p class="test-class"><strong>test message</strong></p>
i have working code this.
paragraphtag = soup.new_tag('p') paragraphtag['class'] = 'test-class' strongtag = soup.new_tag('strong') strongtag.append('test message') paragraphtag.append(strongtag) paragraph.insert_before(paragraphtag)
note insert_before purposely done since part of bigger code need insert_before.
my question - there better way this? or there smaller piece of code can write achieve this? please note tried putting in 1 string , added paragraph. when used find_all search p tags newly added p tag getting skipped. guess did not added.
any input appreciated. thanks
you build snippet html in new beautifulsoup()
object:
html = '<p class="test-class"><strong>test message</strong></p>' snippet = beautifulsoup(html).p.extract() paragraph.insert_before(snippet)
the .extract()
call makes work; detaches elements host document object model.
demo:
>>> bs4 import beautifulsoup >>> soup = beautifulsoup('<html><body/></html>') >>> html = '<p class="test-class"><strong>test message</strong></p>' >>> snippet = beautifulsoup(html).p.extract() >>> snippet <p class="test-class"><strong>test message</strong></p> >>> soup.body.append(snippet) >>> soup <html><body><p class="test-class"><strong>test message</strong></p></body></html>
Comments
Post a Comment