简体   繁体   中英

How to link Python code with HTML webpage?

I have python code that shows a data frame. How can I link the python code to show it as a table in an HTML webpage and use CSS to edit this table? I am using Vs code.

Here is my python code for creating a dataframe.

import requests
import pandas as pd
from bs4 import BeautifulSoup


url = "https://www.worldometers.info/coronavirus/country/Austria/"
soup = BeautifulSoup(requests.get(url).content, "html.parser")

cases, deaths, recovered = soup.select(".maincounter-number")
active_cases, closed_cases = soup.select(".number-table-main")
active_cases_mild, active_cases_serious, _, _ = soup.select(".number-table")

df = pd.DataFrame(
    {
        "Coronavirus Cases": [cases.get_text(strip=True)],
        "Deaths": [deaths.get_text(strip=True)],
        "Recovered": [recovered.get_text(strip=True)],
        "Currently infected": [active_cases.get_text(strip=True)],
        "Closed cases": [closed_cases.get_text(strip=True)],
        "Active cases (mild)": [active_cases_mild.get_text(strip=True)],
        "Active cases (serious)": [active_cases_serious.get_text(strip=True)],
    }
)
print(df)

You can show the table in simple html code just like that for example:

<!DOCTYPE html>
<html lang="en">
<body>
    "Test"
</body>
</html>

I guess this is an option but there certainly have to be better options:

import requests
from bs4 import BeautifulSoup


url = "https://www.worldometers.info/coronavirus/country/Austria/"
soup = BeautifulSoup(requests.get(url).content, "html.parser")

cases, deaths, recovered = soup.select(".maincounter-number")
active_cases, closed_cases = soup.select(".number-table-main")
active_cases_mild, active_cases_serious, _, _ = soup.select(".number-table")

lst = [cases, deaths, recovered, active_cases, closed_cases, active_cases_mild, active_cases_serious]

table_data = ''

for data in lst:
    data = data.text.replace('\n', '')
    table_data += f'<td>{data}</td>'

html = f"""
<!doctype html>
<html>
<head><title>Test</title></head>
<body>

<table>
<tr>
    <th>Coronavirus Cases</th>
    <th>Deaths</th>
    <th>Recovered</th>
    <th>Currently infected</th>
    <th>Closed cases</th>
    <th>Active cases (mild)</th>
    <th>Active cases (serious)</th>
</tr>
<tr>{table_data}</tr>
</table>

</body>
</html>
"""

print(html)
with open('test.html', 'w') as file:
    file.write(html)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM