【问题标题】:Issue in creating a html file from beautiful soup从美丽的汤中创建 html 文件的问题
【发布时间】:2012-04-02 09:30:17
【问题描述】:

这是我使用 BeautifulSoup 的 Python 代码。主要问题是属性。我正在寻找的是, 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()

这是它的输出:

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

谁能告诉我代码中缺少什么?

【问题讨论】:

    标签: python html beautifulsoup


    【解决方案1】:

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

    【讨论】:

    • 你能再清楚一点。我尝试了几件事,但也没有用。例如:我在 for 循环下使用此代码:tag3.insert(i,tag4) 但没有任何效果。
    猜你喜欢
    • 2011-08-07
    • 2012-12-19
    • 2013-10-30
    • 2016-05-19
    • 2023-03-27
    • 1970-01-01
    • 2022-10-20
    • 1970-01-01
    相关资源
    最近更新 更多