使用Beautiful Soup,如何遍历所有嵌入文本?

7 投票
1 回答
4727 浏览
提问于 2025-04-15 11:26

假设我想从HTML中去掉元音字母:

<a href="foo">Hello there!</a>Hi!

变成

<a href="foo">Hll thr!</a>H!

我觉得这个工作可以用Beautiful Soup来完成。那我该怎么选中标签之间的文本,然后对它进行这样的操作呢?

1 个回答

12

假设变量 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>

注意,标签和属性都没有被修改。

撰写回答