如何使用DataFrame将网站中的表数据存储到csv文件#Python

2024-09-30 14:17:50 发布

您现在位置:Python中文网/ 问答频道 /正文

#import libraries
import pandas as pd
import requests #not always required but needed for some sites so doing it this way

url = 'https://fr.wikipedia.org/wiki/Tunis'

page = requests.get(url)
table = pd.read_html(page.text)
df = table[3]

print(df)

df.to_csv('Climate_data_for_Dubai.csv', index=False)


                                  Mois  jan.  fév.  mars  avril  mai  juin  jui.  août  sep.  oct.  nov.  déc.  année
0    Température minimale moyenne (°C)    72    74    83    104  137   173    20   208    19   155   113    82     13
1    Température maximale moyenne (°C)   157   165   181    207  249    29   326   327   297   252   205   167     23
2                   Ensoleillement (h)   146   160   198    225  282   309   357   329   258   217   174   149  2 804
3                  Précipitations (mm)    59    57    47     38   23    10     2     7    36    66    54    63    462
4  Nombre de jours avec précipitations    12    12    11      9    5     3     1     2     6     9    10    12     92

I don't know why it doesn't create a CSV file and store the data inside it. please help me..


Tags: csvimporturldffordatapagetable
1条回答
网友
1楼 · 发布于 2024-09-30 14:17:50

您可以使用pd.read_html将代码缩短为以下内容:

import pandas as pd

df = pd.read_html('https://fr.wikipedia.org/wiki/Tunis')[3]
df.to_csv('Climate_data_for_Dubai.csv', index=False)

相关问题 更多 >