是的,要删除属性,只需使用
del
在
tag.attrs
data = '''
<ul>
<li data-animal-type="bird" data-other="this is other data">Owl</li>
<li data-animal-type="fish">Salmon</li>
<li data-animal-type="spider">Tarantula</li>
</ul>'''
from bs4 import BeautifulSoup
soup = BeautifulSoup(data, 'lxml')
print('Original soup:')
print(soup)
print('-' * 80)
for tag in soup.find_all(lambda t: any(i.startswith('data-') for i in t.attrs)):
for attr in list(tag.attrs):
if attr.startswith('data-'):
del tag.attrs[attr]
print()
print('Soup without data-* tags:')
print(soup)
print('-' * 80)
这张照片:
Original soup:
<html><body><ul>
<li data-animal-type="bird" data-other="this is other data">Owl</li>
<li data-animal-type="fish">Salmon</li>
<li data-animal-type="spider">Tarantula</li>
</ul></body></html>
--------------------------------------------------------------------------------
Soup without data-* tags:
<html><body><ul>
<li>Owl</li>
<li>Salmon</li>
<li>Tarantula</li>
</ul></body></html>
--------------------------------------------------------------------------------