python 3.x - Why is being indent's wrong causes wrong function? -


i cannot understand why error happen. first,i wrote

import urllib.request 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 s in soup.find_all("photo"):     url = s.find_all("image_url")[0].string     name+=1     download_image(url, name) 

by running code,i can 1 image api.but right code can 1000 images api.i fixed indents in first code, code like

import urllib.request 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 s in soup.find_all("photo"):     url = s.find_all("image_url")[0].string     name+=1     download_image(url,name) 

at last,i can 1000 images api. cannot understand why can fixing indent.please give me explanations.

because in first example you're getting image if condition passes:

if not os.path.exists(path): 

and condition pass once because create path:

os.makedirs(path) 

for every other iteration of loop, condition false. code within conditional block doesn't execute.

basically, if block executes if condition true. when move code out of if block, executes regardless of condition.


Comments

Popular posts from this blog

inversion of control - Autofac named registration constructor injection -

verilog - Systemverilog dynamic casting issues -

ios - Change Storyboard View using Seague -