HTML和Python:如何在用python脚本编写的html代码中创建变量

时间:2016-02-27 06:30:25

标签: python html python-2.7 beautifulsoup

from bs4 import BeautifulSoup
import os
import re

htmlDoc="""
<html>
<body>

<table class="details" border="1" cellpadding="5" cellspacing="2" style="width:95%">
  <tr>
    <td>Roll No.</td>
    <td><b>Subject 1</b></td>       
    <td>Subject 2</td>
  </tr>
  <tr>
    <td>01</td>
    <td>Absent</td>     
    <td>Present</td>
  </tr>
  <tr>
    <td>02</td>
    <td>Absent</td>     
    <td>Absent</td>
  </tr>
</table>

</body>
</html>
"""
soup = BeautifulSoup(htmlDoc,"lxml")

#table = soup.find("table",attrs={class:"details"})



html = soup.prettify("utf-8")
with open("/home/alan/html_/output.html", "wb") as file:
    file.write(html)

我使用BeautifulSoup编写HTML代码。在代码中,变量I'vve to make is Present,Absent。在更改某些参数后,我将更改值,将当前更改为不存在,反之亦然。 我要变通/不存在变量'a'。

1 个答案:

答案 0 :(得分:0)

你的意思是使用BeautifulSoup在python数据上从某种形式编写自己的html?如果是这样,以下示例可能对您有用:

from bs4 import BeautifulSoup, Tag
import os

subjects = ['subject1', 'subject2']
vals = [['absent','present'],['absent','absent']] #rows

titles = ['Roll No.'] + subjects

html = """<html>
              <body>
                  <table class="details" border="1" cellpadding="5" cellspacing="2" style="width:95%">
                  </table>
              </body>
          </html>"""
soup = BeautifulSoup(html)

#find table tag
table = soup.find('table')

#add header to table tag
tr = Tag(table, name = 'tr')
for title in titles:
    td = Tag(tr, name = 'td')
    td.insert(0, title)
    tr.append(td)
table.append(tr)

#add data to table one row at a time
for i in range(len(vals[0])):

    tr = Tag(table, name = 'tr')

    td = Tag(tr, name = 'td')
    td.string = str(i+1)
    tr.append(td)

    for val in vals[i]:
        td = Tag(tr, name = 'td')
        td.string = val
        tr.append(td)

    table.append(tr)

os.chdir(os.getcwd())
f = open('test.html','w')
f.write(soup.prettify())
f.close()