想要将数据从 Web 填充到我桌面上的目录中,是否可以为一个 ID 而不是 4 个 ID 执行此操作?



我正在从 wunderground.com 获取数据,然后将其清理并保存到csv文件中。我有一个名为 station 的外部文件.csv其中包含 4 个站点的 id,我需要获取每个站点的所有 12 个月数据,因此我需要将 48 个文件保存到我的桌面数据库中。

以下是车站.csv:

KCASANFR131,37.778,-122.408
KDCWASHI48,38.913,-77.031
IBRITISH359,49.256,-123.245
KNYNEWYO639,40.755,-74.007

到目前为止,我能够从该网站获取数据并将其保存到桌面上名为"数据库"的目录中。

以下是代码运行后的数据库外观:

第一个代码运行时的数据库

所以这看起来是正确的,我只需要为所有四个站点复制它。

这是代码:

import urllib

def getData(month):
url = "https://www.wunderground.com/weatherstation/WXDailyHistory.asp?ID=KMDLAURE5&year=2017&month="+str(month)+"&graphspan=month&format=1"
infile = urllib.urlopen(url)
readLineByLine = infile.readlines()
infile.close()
return readLineByLine

for i in range(1,13):
data = getData(i)
filename = "database/0{}-2017.csv".format(i)
outfile = open(filename,'w')
row_count = len(data)
for j in range(2, row_count):
if(data[j] != '<br>n' and data[j] != 'n'):
outfile.write(data[j])
outfile.close()

现在我正在尝试编辑原始代码,以便它给我的不是 12 个 1 个文件,而是 48 个文件,来自 station 的 4 个站 ID 中的每一个 12 个.csv。

这是代码(现在损坏):

import urllib
def getData(Id, month):
url = "https://www.wunderground.com/weatherstation/WXDailyHistory.asp? ID=" + str(Id) + "&year=2017&month="+str(month)+"&graphspan=month&format=1"
infile = urllib.urlopen(url)
readLineByLine = infile.readlines()
infile.close()
return readLineByLine
f = open('stations.csv', 'r')

for elem in f.readlines():
vals = elem.split(',')

for i in range(1,13):
data = getData(elem, i)
filename = "database/{}-0{}-2017.csv".format(vals[0], i)
outfile = open(filename,'w')
row_count = len(data)
for j in range(2, row_count):
if(data[j] != '<br>n' and data[j] != 'n'):
outfile.write(data[j])
outfile.close()

有了这个,它给出了正确的ID和月份名称,但它没有天气数据。下面是它的样子:

带有 2017 年数据编辑代码的数据库图片

我要做的最后一件事是编辑代码,使其使用 zfill(2),这样我就不会有看起来像 011 的月份,而是 11。

请帮忙

谢谢

对于有关缺失数据的部分,请检查您正在点击的实际网址。 您始终可以先在浏览器中尝试一下。 在我看来,url 中的空格是一个错误:

>>> import urllib
>>> len(urllib.urlopen("https://www.wunderground.com/weatherstation/WXDailyHistory.asp? ID=KCASANFR131&year=2017&month=1&graphspan=month&format=1").readlines())
2
>>> len(urllib.urlopen("https://www.wunderground.com/weatherstation/WXDailyHistory.asp?ID=KCASANFR131&year=2017&month=1&graphspan=month&format=1").readlines())
62

就格式而言,您只需要在字符串中有一个明确的格式说明符。 这应该可以解决问题:

filename = "database/{}-{02}-2017.csv".format(vals[0], i)

最新更新