1
我試圖用lxml將文本插入到html表格中。用lxml插入文本
該表很簡單,它有一個單一的標題。我想解析一個項目列表,每個項目在表格中應該有一行。因此:
--------
| HEAD |
--------
| Item |
--------
| Item |
--------
我已經創建了一個函數,它需要一個路徑和一個模板。路徑用於保存頁面,模板是用於插入數據的.html。我的代碼如下所示:
def genereate_page(path, template):
tree = html.parse(template)
root = tree.getroot()
items = ['Item1', 'Item2', 'Item3', 'Item4']
table = root.findall('.//*[@table="results"]')
for i in items:
row = etree.Element('tr')
data = etree.Element('td')
data.text = i
row.append(data)
table.append(row)
with open(path, 'w') as f:
f.write(etree.tostring(root, pretty_print=True).decode('utf-8'))
我的模板文件看起來像這樣:
<html>
<head>
<title>example</title>
</head>
<body>
<table id="results">
<tr id="header_row">
<th>Test</th>
</table>
</body>
</html>
一切編譯,得到的卻是沒有錯誤,但沒有文字是不斷插入。我只是得到模板返回,但它確實關閉了header_row,所以發生了一些事情。如何使用lxml將項目列表中的文本插入到表中?
感謝那些工作!是否有理由使用[@ id =「results」]而不是[@ table =「results」]來查找表格? – cenh
@cenh因爲在你的HTML模板中,'results'是'id'屬性的值,而不是'table'屬性(模板中甚至沒有這種名爲table的屬性)。請注意,'@ attribute_name'是您在XPath中引用HTML屬性的方式。 – har07