[英]Incomplete download using requests in Python
我正在关注一个我们预测空气质量指数的在线项目。 为此,我们需要首先获取从网站下载的数据。 以下是作者提供的源代码:
import os
import time
import requests
import sys
def retrieve_html():
for year in range(2013,2019):
for month in range(1,13):
if(month<10):
url='http://en.tutiempo.net/climate/0{}-{}/ws-421820.html'.format(month
,year)
else:
url='http://en.tutiempo.net/climate/{}-{}/ws-421820.html'.format(month
,year)
texts=requests.get(url)
text_utf=texts.text.encode('utf=8')
if not os.path.exists("Data/Html_Data/{}".format(year)):
os.makedirs("Data/Html_Data/{}".format(year))
with open("Data/Html_Data/{}/{}.html".format(year,month),"wb") as output:
output.write(text_utf)
sys.stdout.flush()
if __name__=="__main__":
start_time=time.time()
retrieve_html()
stop_time=time.time()
print("Time taken {}".format(stop_time-start_time))
这工作得很好。 现在,我尝试自己编写相同的代码。 这是我的代码:
import os
import time
import requests
import sys
def retrieve_html():
for year in range(2013,2019):
for month in range(1,13):
if(month<10):
url='http://en.tutiempo.net/climate/0{}-{}/ws-421820.html'.format(month, year)
else:
url='http://en.tutiempo.net/climate/{}-{}/ws-421820.html'.format(month, year)
texts=requests.get(url)
text_utf=texts.text.encode("utf=8")
if not os.path.exists("Data/Html_Data/{}".format(year)):
os.makedirs("Data/Html_Data/{}".format(year))
with open("Data/Html_Data/{}/{}.html".format(year,month),"wb") as output:
output.write(text_utf)
sys.stdout.flush()
if __name__=="__main__":
start_time=time.time()
retrieve_html()
stop_time=time.time()
print("Time taken: {}".format(stop_time-start_time))
但是每当我运行这个脚本时,只有第 12 个月的数据被下载,其他月份的数据的 rest 没有被下载。 我使用作者提供的代码进行了检查,虽然我的代码与他的完全相同,但它工作得非常好。 这真让我抓狂。 谁能指出我哪里出错了?
好吧,你应该缩进这个:
texts=requests.get(url)
text_utf=texts.text.encode("utf=8")
if not os.path.exists("Data/Html_Data/{}".format(year)):
os.makedirs("Data/Html_Data/{}".format(year))
with open("Data/Html_Data/{}/{}.html".format(year,month),"wb") as output:
output.write(text_utf)
代码是正确的,只有缩进问题。 以下代码应在内部 for 循环中
texts=requests.get(url)
text_utf=texts.text.encode("utf=8")
if not os.path.exists("Data/Html_Data/{}".format(year)):
os.makedirs("Data/Html_Data/{}".format(year))
with open("Data/Html_Data/{}/{}.html".format(year,month),"wb") as output:
output.write(text_utf)
以下代码应该在外部for循环中
sys.stdout.flush()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.