2012-04-02 42 views
0

这是我使用BeautifulSoup的Python代码。主要问题是属性。我正在寻找的是,th的每个元素都应该分开,但由于某种原因,它只能在一个单独的标签中生成。从美丽的汤创建HTML文件的问题

from BeautifulSoup import BeautifulSoup, Tag 
soup=BeautifulSoup() 
mem_attr=['Description','PhysicalID','Slot','Size','Width'] 
tag1 = Tag(soup, "html") 
tag2 = Tag(soup, "table") 
tag3 = Tag(soup, "tr") 
tag4 = Tag(soup, "th") 
tag5 = Tag(soup, "td") 
soup.insert(0, tag1) 
tag1.insert(0, tag2) 
tag2.insert(0, tag3) 
for i in range(0,len(mem_attr)): 
     tag3.insert(0,tag4) 
     tag4.insert(i,mem_attr[i]) 

print soup.prettify() 

下面是它的输出:

<html> 
<table> 
    <tr> 
    <th> 
    Description 
    PhysicalID 
    Slot 
    Size 
    Width 
    </th> 
    </tr> 
</table> 
</html> 

我所寻找的是这一个。

<html> 
    <table> 
     <tr> 
     <th> 
     Description 
     </th> 
     <th> 
     PhysicalID 
     </th> 
     <th> 
     Slot 
     </th> 
     <th> 
     Size 
     </th> 
     <th> 
     Width 
     </th> 
     </tr> 
    </table> 
    </html> 

任何人都可以告诉我代码中缺少什么吗?

回答

3

你把它放在相同的th。你从来没有告诉它创造多个。

这里是代码更像你想要什么:

from BeautifulSoup import BeautifulSoup, Tag 
soup = BeautifulSoup() 
mem_attr = ['Description', 'PhysicalID', 'Slot', 'Size', 'Width'] 
html = Tag(soup, "html") 
table = Tag(soup, "table") 
tr = Tag(soup, "tr") 
soup.append(html) 
html.append(table) 
table.append(tr) 
for attr in mem_attr: 
    th = Tag(soup, "th") 
    tr.append(th) 
    th.append(attr) 

print soup.prettify() 
+0

你能更加清楚一点。我尝试了几件事情,但那也没用。例如:我在for循环中使用这个代码:'tag3.insert(i,tag4)',但没有任何工作。 – Jack 2012-04-02 01:33:21

+0

我gt。谢啦 – Jack 2012-04-02 01:35:58