迭代一个数字列表并将它们添加到标签中

时间:2011-11-09 14:05:46

标签: python html

所以我有这个表,我希望在Python中查找,找到所有<tr>标签,并将它们转换为<tr id="NUMBER HERE">,其中数字将是列表中的数字是这种格式:

['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '47']

这样做的最佳方式是什么?

基本上,第一个<tr>将成为<tr id="1">第二个<tr id="2">等等。

它并不总是连续的,你可以从20到47看到它。

该表存储为字符串。

我应该指定,目前,它是一个包含多个标签的字符串,即<html><table><tr>blah</tr><tr>blahblah</tr></table></html> - 非常简单。我希望它在字符串中搜索<tr>的实例,并根据tr的位置与列表中的下一个数字替换每个<tr id="NUMBER">

2 个答案:

答案 0 :(得分:7)

使用lxml

import lxml.html as LH

html_table='''
<table>
<tr>
<tr>
<tr>
<tr>
<tr>
</table>
'''

nums=['1','2','20','47','50']
doc=LH.fromstring(html_table)
for tr,n in zip(doc.xpath('//tr'),nums):
    tr.attrib['id']=n
print(LH.tostring(doc,pretty_print=True))

产量

<table>
<tr id="1"></tr>
<tr id="2"></tr>
<tr id="20"></tr>
<tr id="47"></tr>
<tr id="50"></tr>
</table>

答案 1 :(得分:0)

lxml选项很好。如果有一个外部包(sphc这里),这是一个有趣的选项。

import sphc

nums = ['1','2','20','47','50']

tf = sphc.TagFactory()

table = tf.TABLE()
table.rows = [tf.TR(id=num) for num in nums]

print (table)
相关问题