【问题标题】:How to put a number from a csv file into an HTML table?如何将 csv 文件中的数字放入 HTML 表格中?
【发布时间】:2020-06-11 00:06:00
【问题描述】:

我制作了一个网络爬虫来收集冠状病毒数据。我知道这种类型的网站以前做过,但我想这样做是为了个人享受,而且我是初学者,所以我认为这将是一个很好的第一个网站...

无论如何,我需要将我的数据从网络爬虫获取到 HTML 表格中,以显示正确的死亡和病例。我有一个 python 代码文件来获取一个国家的死亡人数,一个来获取病例。如果无论如何我可以在我的 HTML 代码中获取该数字,我会将抓取的数据保存在 csv 中。

我想我要问的是有没有办法把那个数字放在 HTML 表格代码中?

【问题讨论】:

  • 每个国家/地区的数据可在 github (Hopkins) 上找到,您可能需要查看:github.com/CSSEGISandData/COVID-19
  • @BertrandMartel 我想自己做,我需要将数据放入 html 表中。
  • 是的,有办法做到这一点。详细信息将取决于您如何从 CSV 文件中获取数字以及如何构建 HTML 表格——但是您的问题中没有任何线索或代码……
  • 您可以使用 csv 和 sys,但正如 @martineau 指出的那样,您没有办法做任何事情。
  • 我认为我不需要包含我的代码,因为它只是一个带有 tr 和 td 标签的简单 html 表。没有什么特别的。我有一个 csv 文件中的数字。有什么办法可以将该 csv 文件设置为一个变量并在 html 中调用它?

标签: python html web-scraping


【解决方案1】:

HTML 是普通字符串。您可以使用字符串函数创建带有HTML 的字符串,数据在<table> 中,并保存在文件中以在Web 浏览器中显示。

使用for-loop 将每一行数据转换为带有<tr> 的字符串,并添加到HTML 的其余部分。

您也可以使用Jinja 将文件与模板一起使用(例如在Web 框架中Flask),但它仍然需要模板内的for-loop 来生成行。

这样您就可以完全控制HTML


你也可以在pandas中使用to_html

df = pandas.read_csv(filename, ...)
html = df.to_html()

只有<table>才能获得HTML,您可以将其保存在文件中并显示,也可以添加到其他HTML

to_html() 有一些选项可以更改 <table> 中的某些内容,但您可能无法完全控制此表。


编辑:

import pandas as pd

df = pd.read_csv("file.csv")

df.to_html("file.html")

# or

table = df.to_html()
print(table)

html = "<html> <head></head> <body>" + table + "</body> </html>"

fp = open("file.html", "w")
fp.write(html)
fp.close()

编辑:

如果您在 China.csvUK.csv 等分隔文件中有数据,请使用 for-loop

`# --- before loop ---

HTML = "<html> <head><title>All Countries</title> </head> <body>"

# --- loop ---

for country in ['China', 'UK', 'Italy']:
    df = pd.read_csv( country + '.csv' )
    table = df.to_html()
    HTML += "<h1>" + country + "</h1>" + table

# --- after loop ---

HTML += "</body> </html>"    
#print(HTML)

fp = open("output.html", "w")
fp.write(HTML)
fp.close()

如果您在文件夹中拥有所有 CSV 文件,即。 data 那么你可以使用os.listdir()glob.glob()

# --- before loop ---

HTML = "<html> <head><title>All Countries</title> </head> <body>"

folder = 'data'

# --- loop ---

for filename in sorted(os.listdir(folder)):
    if filename.endswith('.csv'):
        country = filename.replace('.csv', '')

        fullpath = os.path.join(folder, filename)

        df = pd.read( fullpath )
        table = df.to_html()

        HTML += "<h1>" + country + "</h1>" + table

# --- after loop ---

HTML += "</body> </html>"    
#print(HTML)

fp = open("output.html", "w")
fp.write(HTML)
fp.close()

编辑:

使用字符串函数创建带有表格的 HTML。

import pandas as pd

# --- example data ---

df = pd.DataFrame({
    'A': [  1,   2,   3],
    'B': ['X', 'Y', 'Z'],
    'C': [0.1, 0.2, 0.3],
})

# --- before loop ---

HTML = """<!DOCTYPE html>

<html>

<head>
   <title>Example Data</title>
</head>

<body>

"""

# --- loop ---

HTML += '<table>\n'

# headers

HTML += '  <tr>\n'
for header in df.columns:
    HTML += '    <th>' + str(header) + '</th>\n'

HTML += '  </tr>\n'

# rows

for index, row in df.iterrows():
    HTML += '  <tr>\n'
    for cell in row:
        HTML += '    <td>' + str(cell) + '</td>\n'
    HTML += '  </tr>\n'

HTML += '</table>\n'

# --- after loop ---

HTML += """
</body>

</html>"""

# --- end ---

print(HTML)

结果:

<!DOCTYPE html>

<html>

<head>
   <title>Example Data</title>
</head>

<body>

<table>
  <tr>
    <th>A</th>
    <th>B</th>
    <th>C</th>
  </tr>
  <tr>
    <td>1</td>
    <td>X</td>
    <td>0.1</td>
  </tr>
  <tr>
    <td>2</td>
    <td>Y</td>
    <td>0.2</td>
  </tr>
  <tr>
    <td>3</td>
    <td>Z</td>
    <td>0.3</td>
  </tr>
</table>

</body>

</html>

同样使用pandas to_html()

import pandas as pd

# --- example data ---

df = pd.DataFrame({
    'A': [  1,   2,   3],
    'B': ['X', 'Y', 'Z'],
    'C': [0.1, 0.2, 0.3],
})

# --- before loop ---

HTML = """<!DOCTYPE html>

<html>

<head>
   <title>Example Data</title>
</head>

<body>

"""

# --- loop ---

HTML += df.to_html()

# --- after loop ---

HTML += """
</body>

</html>"""

# --- end ---

print(HTML)

结果:

<!DOCTYPE html>

<html>

<head>
   <title>Example Data</title>
</head>

<body>

<table border="1" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th></th>
      <th>A</th>
      <th>B</th>
      <th>C</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th>0</th>
      <td>1</td>
      <td>X</td>
      <td>0.1</td>
    </tr>
    <tr>
      <th>1</th>
      <td>2</td>
      <td>Y</td>
      <td>0.2</td>
    </tr>
    <tr>
      <th>2</th>
      <td>3</td>
      <td>Z</td>
      <td>0.3</td>
    </tr>
  </tbody>
</table>
</body>

</html>

【讨论】:

  • 那么在带有csv的()中我要放csv文件名吗?
  • 是的,你放了文件名和许多其他选项——比如分隔符、跳过标题等。见 doc pandas.read_csv
  • 我还是一头雾水。您想通过电子邮件为我提供更多帮助吗?不想的话也没关系。我是编码初学者,我真的需要帮助
  • 有什么问题? import pandasdf = pandas.read_csv("file.csv")html = df.to_html()print(html)最终df.to_html("file.html")
  • 但是在 html 方面我该怎么做才能将数据准确地导入到我想要的位置?
猜你喜欢
  • 2020-10-08
  • 2020-11-09
  • 2015-02-03
  • 2019-03-30
  • 1970-01-01
  • 1970-01-01
  • 2012-10-12
  • 2011-11-01
  • 1970-01-01
相关资源
最近更新 更多