How to get css attribute of a lxml element?

2020-07-30 02:18发布

问题:

I want to find a fast function to get all style properties of a lxml element that take into account the css stylesheet, the style attribute element and tackle the herit issue.

For example :

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.b {color:pink;}

python :

elements = document.xpath('//p')
print get_style(element[0]) 
>{color:red,font-size:12px}
print get_style(element[1]) 
>{color:pink,font-size:12px}
print get_style(element[2]) 
>{color:blue,font-size:12px}

Thanks

回答1:

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) 


标签: python css lxml