Des*_*ond 2 html python trim beautifulsoup
我的字符串 html 中有一些段落如下所示:
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
</p>
Run Code Online (Sandbox Code Playgroud)
我想删除标签内的空白p并将其变成:
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua</p>
Run Code Online (Sandbox Code Playgroud)
请注意,p像这样的标签应该保持更改:
<p class="has-media media-640"><img alt="Lorem ipsum dolor sit amet" height="357" src="http://www.example.com/img/lorem.jpg" width="636"/></p>
Run Code Online (Sandbox Code Playgroud)
我想要的是:
for p in soup.findAll('p'):
replace p.string with trimmed text
Run Code Online (Sandbox Code Playgroud)
您可以将文本替换为element.string.replace_with()方法:
for p in soup.find_all('p'):
if p.string:
p.string.replace_with(p.string.strip())
Run Code Online (Sandbox Code Playgroud)
演示:
>>> from bs4 import BeautifulSoup
>>> soup = BeautifulSoup('''\
... <p>
... Text with whitespace
... </p>
... <p>No whitespace</p>
... <p><span><img /></span></p>
... ''')
>>> for p in soup.find_all('p'):
... if p.string:
... p.string.replace_with(p.string.strip())
...
u'\n Text with whitespace\n'
u'No whitespace'
>>> print str(soup)
<html><head></head><body><p>Text with whitespace</p>
<p>No whitespace</p>
<p><span><img/></span></p>
</body></html>
Run Code Online (Sandbox Code Playgroud)
这只会去除标签中直接包含的空白。如果包含其他标签,则不会发生剥离。
您可以使用该element.strings序列来处理<p>其中包含嵌套标签的标签。我不会修剪所有空格;如果存在,请在每个字符串周围留一个空格:
whitespace = u' \t\n\r\x0a' # extend as needed
for p in soup.find_all('p'):
for string in list(p.strings): # copy so we can replace some
left = string[:1] in whitespace
right = string[-1:] in whitespace
if not left and not right:
continue # leave be
new = string
if left:
new = ' ' + new.lstrip()
if right:
new = new.rstrip() + ' '
string.replace_with(new)
Run Code Online (Sandbox Code Playgroud)
演示:
>>> soup = BeautifulSoup('''\
... <p>
... Text with whitespace
... </p>
... <p>No whitespace</p>
... <p>
... A nested
... <span>tag</span>
... is not a problem
... </p>
... ''')
>>> whitespace = u' \t\n\r\x0a' # extend as needed
>>> for p in soup.find_all('p'):
... for string in list(p.strings): # copy so we can replace some
... left = string[:1] in whitespace
... right = string[-1:] in whitespace
... if not left and not right:
... continue # leave be
... new = string
... if left:
... new = ' ' + new.lstrip()
... if right:
... new = new.rstrip() + ' '
... string.replace_with(new)
...
u'\n Text with whitespace\n'
u'\n A nested \n '
u'\n is not a problem\n'
>>> print str(soup)
<html><head></head><body><p> Text with whitespace </p>
<p>No whitespace</p>
<p> A nested <span>tag</span> is not a problem </p>
</body></html>
Run Code Online (Sandbox Code Playgroud)