【问题标题】:Table creating gets messed up表创建搞砸了
【发布时间】:2013-08-27 00:37:08
【问题描述】:

我正在尝试在 python 中使用下面的 HTML 代码创建一个表格,它适用于大多数情况,但在某些情况下,表格会像下面那样混乱,请参阅屏幕截图..任何关于错误的输入?如何调试它?任何解决方法来修复它?非常感谢任何输入

混乱行的 HTML 源代码:http://pastie.org/8263837

  ...........
  ...........
  GerritMailBody = GerritMailBody + "<td>" + GerritInfo['TargetName'].rstrip('\n') + "</td>"
  GerritMailBody = GerritMailBody + "<td>" + GerritInfo['Assignee'].rstrip('\n') + "</td>"
  usernames.append(GerritInfo['Assignee'].rstrip('\n'))

  #Below is the block that is getting messed up
  GerritMailBody = GerritMailBody + "<td height=\"150\%\">"
  GerritMailBody = GerritMailBody + "<table>"  
  for item in GerritInfo['GerritUrl']:
    GerritMailBody = GerritMailBody + "<tr>"
    GerritMailBody = GerritMailBody + "<td>"
    GerritMailBody = GerritMailBody + item.rstrip('\n/') + "<br>"
    GerritMailBody = GerritMailBody + "</td>"
    GerritMailBody = GerritMailBody + "</tr>"

  GerritMailBody = GerritMailBody + "</table>"
  GerritMailBody = GerritMailBody + "</td>"

  ............
  ............

【问题讨论】:

  • 发布输入数据并输出 HTML(来源,不是图片)
  • @MarioRossi - 图片显示了输出...我已经分享了导致此问题的源代码。第 5 行应该与第 4 行格式相同,但如您所见搞砸了。
  • @user2125827 他的意思是 HTML 输出,而不是视觉输出。那没用
  • 另外,向我们展示第 4 行和第 5 行的 item 会很有帮助。一个很可能的问题是第 5 项中间有 HTML 和/或未转义的尖括号……
  • 注意 - 我已经回滚了你的更改 - 这样“破坏”你自己的帖子是不公平的 - 它会使人们花时间为你提供的答案无效

标签: python html


【解决方案1】:

您的 HTML 有很多很多问题,但最明显的问题是在第 19 行引起您的问题:

&lt;td style='padding:.75pt .75pt .75pt .75pt'&gt;&lt;table!&gt;&lt;/td&gt;

&lt;table!&gt;“标签”在那里做什么?在提出问题之前,您是否阅读了它提供给您的 HTML?

【讨论】:

  • 是的,那可能是那个……知道为什么根据上面共享的代码会去那里吗?
【解决方案2】:

在 python 中以这种方式构造 html 根本不可读且难以维护。切换到mako之类的模板引擎:

from mako.template import Template
print Template("hello ${data}!").render(data="world")

使用您的消息正文模板定义一个 html 文件,通过render 填充数据并将消息作为字符串获取:

from mako.template import Template

mytemplate = Template(filename='body.html')
print mytemplate.render(data=data)

相信我,这会让你的生活更轻松,睡眠更安宁。


HTML 混乱的可能原因是您插入到 html 中的数据包含一些应该转义的字符(&lt;&lt;&amp;)。考虑在您插入的每个项目上调用cgi.escape()。另见:What's the easiest way to escape HTML in Python?

同样,转义在大多数模板引擎中都是开箱即用的。

希望对您有所帮助。

【讨论】:

  • 我现在无法更改代码..需要让它以这种方式工作..完整代码是pastie.org/8263783 ..你可以从代码中看出什么
  • @user2125827 我敢打赌,您在那里输入的数据有时需要转义一些字符。
  • @user2125827 如果你切换到mako - 它会让你逃避 :) 不要重新发明轮子。
【解决方案3】:

调试问题的步骤:

  1. 确定导致问题的条件,尤其是数据集。
  2. 减少。从数据集中删除信息,直到您确切了解导致程序失败的原因。
  3. 仅使用该信息调试程序。
  4. 使用完整数据集和之前的测试进行回归测试。

【讨论】:

  • @user2125827 第一眼什么都没有。
  • @Mario - 混乱行的 HTML 输出是 paste.org/8263837
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-10-30
  • 1970-01-01
  • 2015-07-17
  • 2010-10-15
  • 2012-04-14
  • 1970-01-01
相关资源
最近更新 更多