您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

使用Beautiful Soup Python模块用纯文本替换标签

使用Beautiful Soup Python模块用纯文本替换标签

适用于您的特定示例的方法是:

from BeautifulSoup import BeautifulSoup

ht = '''
<div id="abc">
    some long text goes <a href="/"> here </a> and hopefully it 
    will get picked up by the parser as content
</div>
'''
soup = BeautifulSoup(ht)

anchors = soup.findAll('a')
for a in anchors:
  a.prevIoUsSibling.replaceWith(a.prevIoUsSibling + a.string)

results = soup.findAll(text=lambda(x): len(x) > 20)

print results

发出

$ python bs.py
[u'\n    some long text goes  here ', u' and hopefully it \n    will get picked up by the parser as content\n']

当然,你可能需要采取多一点关怀,即,如果没有a.string,或者a.prevIoUsSiblingNone-你需要合适的if语句来采取这种极端情况的照顾。但我希望这个总体思路能对您有所帮助。(事实上,你可能想_也_ 合并 @H_404_21@下一个 兄弟,如果它是一个字符串-与您的启发式不知道如何播放len(x) > 20,但说,例如,你有两个9个字符的字符串与<a>中间包含5个字符的字符串,也许您想将其作为“ 23个字符的字符串”使用呢?我不知道是因为我不理解您启发式搜索的动机)。

我想除了<a>标签,您还希望删除其他标签,例如<b><strong>,也许<p>和/或<br>,等等…?我想这也取决于启发式技术背后的实际想法!

python 2022/1/1 18:45:56 有303人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶