我想找到一个快速函数来获取 lxml 元素的所有样式属性,该函数考虑了 css 样式表、样式属性元素并解决了继承问题。
例如:
html:
<body>
<p>A</p>
<p id='b'>B</p>
<p style='color:blue'>B</p>
</body>
样式:
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}
谢谢
最佳答案
您可以结合使用 lxml 和 cssutils 来完成此操作. This cssutils 实用程序模块应该能够执行您的要求。将 cssutils 与该模块一起安装,然后运行以下代码:
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 - 如何获取 lxml 元素的 css 属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9519906/