使用lxml设置行的属性

时间:2017-03-04 23:02:57

标签: python html attributes lxml

我想使用一些逻辑来识别html文档中表格的特定行,然后将该行的背景颜色设置为特定颜色

此代码执行此操作但它未正确设置行颜色 - 因为该行不显示新颜色

for row in new_tree.xpath('//tr'):
    if row_counter == 1:
        continue
    row.set('background-color','#DDA0DD')
    row_text = row.text_content().lower()
    if 'test_word' in row_text:
        row_counter += 1

这是其中一项结果 - 但无论使用何种浏览器打开文件,行颜色仍为白色

<tr background-color="#DDA0DD">

我相信html代码的语法是错误的,但不知道如何在lxml中纠正它,除了将行转换为字符串然后尝试将样式插入字符串 - 这似乎太笨重了

1 个答案:

答案 0 :(得分:1)

而不是row.set('background-color','#DDA0DD'),你应该使用它:

row.set("style", "background-color: #DDA0DD")

该代码将生成正确的内联样式标记:

<tr style="background-color: #DDA0DD">
相关问题