2012-04-02 38 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