【问题标题】:Why is being indent's wrong causes wrong function?为什么缩进的错误会导致错误的功能?
【发布时间】:2017-04-06 13:51:04
【问题描述】:

我不明白为什么会发生这个错误。 首先,我写了

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 中获取 1 张图片。但是原本正确的代码可以从 API 中获取 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 张图片。但是我不明白为什么我可以通过修复缩进来做到这一点。请给我一些解释。

【问题讨论】:

  • 因为它是 Python...?

标签: python-3.x tensorflow


【解决方案1】:

因为在第一个示例中,您只有在条件通过时才能获取图像:

if not os.path.exists(path):

而且该条件只会通过一次,因为您会立即创建路径:

os.makedirs(path)

对于循环的每个其他迭代,条件为假。所以代码条件块不会执行。

基本上,if 块仅在条件为真时执行。当您将代码移出 if 块时,无论条件如何,它都会始终执行。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-04
    • 2020-07-16
    • 2014-06-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多