[英]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.