How to get css attribute of a lxml element?

喜你入骨 提交于 2019-12-04 19:45:20

You can do this with a combination of lxml and cssutils. This cssutils utility module should be able to do what you're asking. Install cssutils along with that module, then run the following code:

from style import *

html = """<body>
    <p>A</p>
    <p id='b'>B</p>
    <p style='color:blue'>B</p>
</body>"""

css = """body {color:red;font-size:12px}
p {color:yellow;}
p.b {color:green;}"""


def get_style(element, view):
    if element != None:
        inline_style = [x[1] for x in element.items() if x[0] == 'style']
        outside_style =  []
        if view.has_key(element):
            outside_style = view[element].getCssText()
        r = [[inline_style, outside_style]]
        r.append(get_style(element.getparent(), view))
        return r
    else:
        return None

document = getDocument(html)
view = getView(document, css)

elements = document.xpath('//p')
print get_style(elements[0], view) 
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!