2012-04-02 8 views
0

BeautifulSoupを使用している私のpythonコードはここにあります。主な問題は属性です。私が探しているのは、thの各要素を分離する必要がありますが、何らかの理由で1つの個別タグ内で生成を続けているということです。ここで美しいスープから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

+0

I gt it。ありがとう – Jack

関連する問題