假设我想从HTML中删除元音:
<a href="foo">Hello there!</a>Hi!
变为
<a href="foo">Hll thr!</a>H!
我认为这是Beautiful Soup的工作。如何在标签之间选择文本并对其进行操作?
答案 0 :(得分:10)
假设变量test_html
具有以下html内容:
<html>
<head><title>Test title</title></head>
<body>
<p>Some paragraph</p>
Useless Text
<a href="http://stackoverflow.com">Some link</a>not a link
<a href="http://python.org">Another link</a>
</body></html>
这样做:
from BeautifulSoup import BeautifulSoup
test_html = load_html_from_above()
soup = BeautifulSoup(test_html)
for t in soup.findAll(text=True):
text = unicode(t)
for vowel in u'aeiou':
text = text.replace(vowel, u'')
t.replaceWith(text)
print soup
打印:
<html>
<head><title>Tst ttl</title></head>
<body>
<p>Sm prgrph</p>
Uslss Txt
<a href="http://stackoverflow.com">Sm lnk</a>nt lnk
<a href="http://python.org">Anthr lnk</a>
</body></html>
请注意,标签和属性不受影响。