【问题标题】:Set an attribute of a row using lxml使用 lxml 设置行的属性
【发布时间】:2017-03-04 23:02:56
【问题描述】:

我想使用一些逻辑来识别 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 中更正它——这似乎太笨拙了

【问题讨论】:

  • 看来你需要设置一个合适的内联样式:row.set("style", "background-color: #DDA0DD").
  • @mzijn 感谢帖子作为答案,我会给你这个有帮助的问题并解决我的问题

标签: python html attributes lxml


【解决方案1】:

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

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

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

<tr style="background-color: #DDA0DD">

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-02
    • 1970-01-01
    • 2018-09-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多