从beautiful soup创建html文件时出现的问题

2024-10-16 23:37:55 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我的python代码使用beauthoulsoup。主要问题是属性。我要找的是,th的每个元素都应该分开,但是由于某种原因它只在一个单独的标记中生成。在

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()

以下是其输出:

^{pr2}$

我要找的是这个。在

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

有人能告诉我密码里缺少什么吗?。在


Tags: htmltagtabledescriptionmemtrattrinsert
1条回答
网友
1楼 · 发布于 2024-10-16 23:37:55

你把它放在同一个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()

相关问题 更多 >