【问题标题】:HTML and Python : How to make variables in a html code written in a python script [closed]HTML和Python:如何在用python脚本编写的html代码中创建变量[关闭]
【发布时间】:2016-06-10 13:04:24
【问题描述】:
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 代码。在代码中,我要做的变量是 Present, Absent。更改某些参数后,我必须更改值,将存在更改为不存在,反之亦然。 我必须将 pesent/absent 设为变量 'a'。

【问题讨论】:

  • 你能澄清你的问题吗?目前尚不清楚您遇到了什么问题。考虑包含您拥有的输入的一小部分(包括程序变量,而不仅仅是 HTML)以及您想要的确切输出。

标签: python html python-2.7 beautifulsoup


【解决方案1】:

您的意思是使用 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()

【讨论】:

  • 非常感谢,这就是你一直在寻找的。我需要的代码需要一些修改。我会试着做这些,如果我有任何疑问,我会问:)
  • 我需要一个程序,以便我可以将大约 10 名学生的出勤率存储在一个 html 文件中,出勤率(无论是否存在)将从一个数组中获取。那我该怎么做呢?
猜你喜欢
  • 1970-01-01
  • 2014-04-19
  • 1970-01-01
  • 2013-08-11
  • 1970-01-01
  • 2017-02-22
  • 1970-01-01
  • 2021-04-03
  • 1970-01-01
相关资源
最近更新 更多