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
omg21
V2EX  ›  Python

Python 除了 BS4,还有其他能精简 html 代码的库吗?

  •  
  •   omg21 · 2017-05-29 14:56:47 +08:00 · 3173 次点击
    这是一个创建于 2530 天前的主题,其中的信息可能已经有所发展或是发生改变。

    《 span lang="EN-US" style="font-size: 16pt;"》天空《/span 》《 p class="MsoNormal" style="text-indent:28.0pt;mso-char-indent-count:2.0;line-height:20.0pt;mso-line-height-rule:exactly"》

    我想把类似上面这样的 html 代码(为了方便发布,我把尖括号换成了《》)精简下,精简成下面这样:

    《 span 》天空《/span 》《 p style="text-indent:28.0pt;line-height:20.0pt;"》

    能看出,我把《 span 》中的 lang 和字号属性删掉了,把《 p 》中 style 属性里的首行缩进和行高留了下来,删除了其他的。 我想知道除了 BS4,其他还有能处理我这个需求的库吗? BS4 能处理 lang、class 这样的属性,但是 style 里面的属性没法处理。

    11 条回复    2017-05-30 14:22:31 +08:00
    7sDream
        1
    7sDream  
       2017-05-29 15:07:50 +08:00
    BS 可以获取到 inline style 的,用 element['style'] 就行,不过如果如果你是要把 style 当作一个 dict 这种来处理 BS 好像确实没有自带。

    不过你可以把 style string 喂给一个 CSS parser,然后按要求处理完再写回去,这样应该可以吧。

    Python 的 CSS parser 应该有很多吧……
    bestkayle
        2
    bestkayle  
       2017-05-29 15:32:20 +08:00
    pyquery
    lxml
        3
    lxml  
       2017-05-29 15:39:04 +08:00
    只针对这个例子,我同意一楼的,我印象中似乎找不到能单独处理某个属性中的某个子属性,把 style 拎出来,按照";"分割成 dict,自己写个函数再拼装回去,text-indent line-heigh,不是很优雅,但好像没有什么更好的解决方案的,我已知的库最小处理单元就是属性本身了。
    dsg001
        4
    dsg001  
       2017-05-29 15:48:25 +08:00
    lxml,w3lib 这两个可以处理一部分,style 需要自己写处理器
    omg21
        5
    omg21  
    OP
       2017-05-29 18:27:39 +08:00
    @7sDream
    @lxml
    @dsg001
    看来只能自己再写函数了,其实我觉得过渡依赖 bs4 也不是好事,就怕以后升级某些功能被修改了更麻烦。
    aljun
        6
    aljun  
       2017-05-29 19:03:19 +08:00
    @7sDream 好久不见 7s。。。
    anuan
        7
    anuan  
       2017-05-29 19:16:11 +08:00
    不太理解这个需求 如果只是几个标签的解个 css 需要保留 其他的属性都删除 直接用正则比较好
    mseasons
        8
    mseasons  
       2017-05-30 01:01:08 +08:00
    lxml?
    justtery
        9
    justtery  
       2017-05-30 09:48:32 +08:00 via Android
    pyquery 滑稽
    omg21
        10
    omg21  
    OP
       2017-05-30 13:25:40 +08:00
    @anuan 最麻烦的地方在 style 里,比如有一些表格的 style 里会有表格线是需要保留的,但同时还有一些像字体字号之类的需要删除的。用正则不太好做。
    7sDream
        11
    7sDream  
       2017-05-30 14:22:31 +08:00
    @aljun 倒是真的好久没上 V2 了……
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2362 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 31ms · UTC 12:23 · PVG 20:23 · LAX 05:23 · JFK 08:23
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.