如何用Python(XPath、lxml、HTMLBuilder)实现两表格并排
让两个表格左右并排的解决方案
嘿,我明白你现在的问题——生成的两个表格默认上下排列,想要改成左右并排对吧?这其实是HTML元素的默认布局导致的:<table>是块级元素,默认会占满整个可用宽度,所以两个表格自然会上下堆叠。
我们可以用CSS Flexbox布局来轻松解决这个问题,只需要把两个表格放在一个设置了display: flex的容器里就行。下面是修改后的完整代码,我还顺便修正了代码里的小错误(比如背景颜色值多写了一个#,会导致样式失效):
import time import lxml.html.builder as html from lxml import etree # 生成第一个表格(P1-PreLive) xmlData_p1 = etree.parse("http://17.19.8.39:8095/this/ressources/p1") nodeData_p1 = xmlData_p1.getroot() # 构建规范的表格结构(表头放在TR内) nodeTable = html.TABLE( html.TR( html.TH("User-Id"), html.TH("conditions"), html.TH("name") ), style="border-collapse: collapse;" # 可选:让表格边框合并更美观 ) # 添加表格标题(语义化标签) nodeTable.append(html.CAPTION("P1-PreLive", style="font-weight: bold; margin-bottom: 8px;")) # 填充表格数据 for nodeVin in nodeData_p1.xpath("./user[@condition = 'fresh']|./user[@condition = 'dirty']"): nodeRow = html.TR( html.TD(nodeVin.attrib['id'], style="background-color:#FF0000; padding: 8px; border: 1px solid #000;"), html.TD(nodeVin.attrib['condition'], style="background-color:#FF0000; padding: 8px; border: 1px solid #000;"), html.TD(nodeVin.attrib['name'], style="background-color:#FF0000; padding: 8px; border: 1px solid #000;") ) nodeTable.append(nodeRow) # 生成第二个表格(P3-TuI) xmlData_p3 = etree.parse("http://17.19.8.39:8095/this/ressources/p3") nodeData_p3 = xmlData_p3.getroot() nodeTable2 = html.TABLE( html.TR( html.TH("User-Id"), html.TH("conditions"), html.TH("name") ), style="border-collapse: collapse;" ) nodeTable2.append(html.CAPTION("P3-TuI", style="font-weight: bold; margin-bottom: 8px;")) for nodeVin in nodeData_p3.xpath("./user[@condition = 'fresh']|./user[@condition = 'dirty']"): nodeRow = html.TR( html.TD(nodeVin.attrib['id'], style="background-color:#e5e5e5; padding: 8px; border: 1px solid #000;"), html.TD(nodeVin.attrib['condition'], style="background-color:#e5e5e5; padding: 8px; border: 1px solid #000;"), html.TD(nodeVin.attrib['name'], style="background-color:#e5e5e5; padding: 8px; border: 1px solid #000;") ) nodeTable2.append(nodeRow) # 创建Flex容器,实现表格左右并排 flex_container = html.DIV( nodeTable, nodeTable2, style="display: flex; gap: 30px; margin: 20px;" # gap控制表格间距,margin控制容器外边距 ) # 生成完整的HTML文档(包含标准的html和body标签) full_html = html.HTML( html.BODY(flex_container) ) # 写入最终HTML文件 with open("out5.html", "wb") as f: f.write(etree.tostring(full_html, pretty_print=True))
关键修改点说明:
- Flex容器:新增了一个
<div>容器并设置display: flex,容器内的表格会自动在一行排列;如果需要强制不换行,可以添加flex-wrap: nowrap样式。 - 修正颜色值:把代码里的
##FF0000改成#FF0000,多一个#会导致CSS样式失效。 - 规范表格结构:将表头放在
<TR>标签内(原代码直接把TH加到TABLE下不符合HTML规范),用<CAPTION>标签显示表格标题,更符合语义化要求。 - 样式优化:给表格添加了边框、内边距,让表格视觉效果更清晰,你可以根据需求调整这些样式参数。
这样生成的HTML文件里,两个表格就会整齐地左右并排显示啦!
内容的提问来源于stack exchange,提问作者123 bodyuilding
相关产品推荐
相关产品推荐

