2017-04-06 117 views
-1

我不明白爲什麼會發生這種錯誤。 首先,我通過運行此代碼寫爲什麼縮進的錯誤原因是錯誤的功能?

import urllib.request 
from bs4 import BeautifulSoup 
import time 
import os 

def download_image(url,name): 
    path = "./scrape_image/" 
    imagename = str(name) + ".jpg" 

    if not os.path.exists(path): 
     os.makedirs(path) 

     print(path) 
     urllib.request.urlretrieve(url,path+imagename) 


url = "https://api.XXXkeyword=YYY&limit=1000" 
response = urllib.request.urlopen(url) 
rss = response.read().decode("utf-8") 

soup = BeautifulSoup(rss, "xml") 

name=0 
for s in soup.find_all("photo"): 
    url = s.find_all("image_url")[0].string 
    name+=1 
    download_image(url, name) 

,我可以從API.But得到1個圖像原本正確的代碼可以從API.I獲得1000張圖像中的第一個代碼縮進固定,所以我的代碼就像

import urllib.request 
from bs4 import BeautifulSoup 
import time 
import os 

def download_image(url,name): 
    path = "./image/" 
    imagename = str(name) + ".jpg" 

    if not os.path.exists(path): 
     os.makedirs(path) 

    print(path) 
    urllib.request.urlretrieve(url, path+imagename) 
    time.sleep(1) 


url = "https://api.XXXkeyword=YYY&limit=1000" 
response = urllib.request.urlopen(url) 
rss = response.read().decode("utf-8") 

soup = BeautifulSoup(rss, "xml") 

name = 0 
for s in soup.find_all("photo"): 
    url = s.find_all("image_url")[0].string 
    name+=1 
    download_image(url,name) 

最後,我可以從API獲得1000個圖像。但我不明白爲什麼我可以通過修改縮進來做到這一點。請給我一些解釋。

+2

因爲它是Python ...? – dasdingonesin

回答

0

因爲在第一個例子,如果你的條件通過你只得到圖像:

if not os.path.exists(path): 

這情況只會通過一次因爲你馬上創建路徑:

os.makedirs(path) 

對於循環的每一次迭代,條件都是錯誤的。所以代碼之內的條件塊不執行。

基本上,僅當條件爲真時纔會執行if塊。將if塊的代碼移出時,無論條件如何,它都會始終執行。

相關問題