V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
tioover
V2EX  ›  Python

python 如何过滤 HTML标签?

  •  
  •   tioover ·
    tioover · 2012-05-21 20:43:51 +08:00 · 12938 次点击
    这是一个创建于 4356 天前的主题,其中的信息可能已经有所发展或是发生改变。
    17 条回复    1970-01-01 08:00:00 +08:00
    wong2
        1
    wong2  
       2012-05-21 20:46:43 +08:00   ❤️ 1
    VeryCB
        2
    VeryCB  
       2012-05-21 20:48:23 +08:00   ❤️ 1
    VeryCB
        3
    VeryCB  
       2012-05-21 20:49:33 +08:00
    lackrp
        4
    lackrp  
       2012-05-21 20:54:58 +08:00   ❤️ 1
    过滤是指要去掉么?

    import re
    pattern = re.compile(r'<.*?>')
    pattern.sub('', html)
    gee
        5
    gee  
       2012-05-21 20:55:50 +08:00
    @VeryCB 你说得一点都不靠谱吧...你给的都是解析html的...
    phuslu
        6
    phuslu  
       2012-05-21 20:57:02 +08:00   ❤️ 1
    python readability
    VeryCB
        7
    VeryCB  
       2012-05-21 20:57:36 +08:00
    @gee 初学者...过滤不是把Html标签去掉然后提取内容么?
    eric_q
        8
    eric_q  
       2012-05-21 21:03:18 +08:00
    我……我还是想用shell
    gee
        9
    gee  
       2012-05-21 21:03:23 +08:00
    @VeryCB 问题是不了解具体的html结构啊。当然了,用PyQuery直接取全体的text()也可以,但是有点绕路了
    TheC
        10
    TheC  
       2012-05-21 21:20:18 +08:00
    @lackrp 你这哪里是过滤html标签,误伤也太大了
    lackrp
        11
    lackrp  
       2012-05-21 21:22:15 +08:00
    @TheC 正确的html的话,这样应该不会误伤啊
    eerie
        12
    eerie  
       2012-05-21 21:33:40 +08:00   ❤️ 1
    TheC
        13
    TheC  
       2012-05-21 21:35:25 +08:00
    @lackrp 仔细想想确实是,抱歉刚才回的太快了,理所当然觉得除了html标签还有其他被<>包括的文本了:)
    tioover
        14
    tioover  
    OP
       2012-05-21 21:54:03 +08:00
    @lackrp 额。我的意思是过滤掉诸如<sript><iframe>之类的标签只允许一些安全的标签,为了安全……
    cute
        15
    cute  
       2012-05-22 20:41:05 +08:00
    @tioover

    from BeautifulSoup import BeautifulSoup
    soup = BeautifulSoup('<html><p>abc</p><script></script><br />abc</html>')
    for tag in soup.recursiveChildGenerator():
    .... if hasattr(tag, 'name') and tag.name in ['script', 'iframe']:
    ........tag.extract()
    print soup.renderContents('utf-8')
    leiz
        16
    leiz  
       2012-05-22 20:42:50 +08:00
    @tioover

    如果只是过滤部分标签,干嘛不直接穷举好了?
    magicshui
        17
    magicshui  
       2012-05-22 21:08:14 +08:00
    BeautifulSoup感觉简单些~
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5401 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 33ms · UTC 07:03 · PVG 15:03 · LAX 00:03 · JFK 03:03
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.