python - 如何获取 lxml 元素的 css 属性?

标签 python css lxml

我想找到一个快速函数来获取 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/

相关文章:

iphone - 纯CSS检测iPhone/iPad

Python BeautifulSoup 相当于 lxml make_links_absolute

python - WordNet:迭代同义词集

python - python-redis:ConnectionError:写入套接字时发生错误32。 pipe 坏了?

python - 必须以实例作为第一个参数调用未绑定(bind)方法 - python

css - Kendo ui if else angularjs

python - 不清楚哪个 Python 版本用于远程调试 (Eclipse Pydev)

html - 如何使用 CSS 在同一行中制作两条垂直线

xpath - 如何使用 xpath 选择文本最长的节点?

python - 使用 lxml 解析 xml - 提取元素值