开发者

Preserve space when stripping HTML with Beautiful Soup

开发者 https://www.devze.com 2023-03-28 03:06 出处:网络
from BeautifulSoup import BeautifulSoup html = \"<html><p>Para 1. Words</p><p>Merge. Para 2<blockquote>Quote 1<blockquote>Quote 2</p></html>\"
from BeautifulSoup import BeautifulSoup

html = "<html><p>Para 1. Words</p><p>Merge. Para 2<blockquote>Quote 1<blockquote>Quote 2</p></html>"
print html
soup = BeautifulSoup(html)
print u''.join(soup.findAll(text=True))

The out put of this code is "Para 1 WordsMerge. Para 2Quote 1Qu开发者_JAVA百科ote 2".

I don't want the last word of paragraph one merging with the first word of paragraph two. eg. "Para 1 Words Merge. Para 2 Quote 1 Quote 2". Can this be achieved using the BeautifulSoup library?


And if you are using get_text() in version 4.x:

from bs4 import BeautifulSoup
...
...
soup.get_text(" ")


Just join the pieces with a space:

print u' '.join(soup.findAll(text=True))
0

精彩评论

暂无评论...
验证码 换一张
取 消