【发布时间】:2019-03-18 22:23:51
【问题描述】:
我编写了一个小型 Python 应用程序,但它没有按我的计划运行。 我希望程序询问用户他/她想在他/她的驱动器上保存多少张来自 Unsplash 的带有所选标签的图像。
res=requests.get("https://unsplash.com/search/photos" + "/" + " ".join(sys.argv[1:]))
res.raise_for_status
soup=bs4.BeautifulSoup(res.text)
elemLinks=soup.select('img._2zEKz')
numb=int(input("How many images do you want to save?"))
之后,我想一个接一个地打开图像,并询问用户是否要保存这个特定的图像,直到它达到一定数量。
numOpen=int(min(50,len(elemLinks)))
imagesSaved=0
i=0
while imagesSaved < numb and i<numOpen:
try:
src=elemLinks[i].get("src")
if src==None:
i+=1
continue
webbrowser.open(elemLinks[i].get("src"))
photoUrl=elemLinks[i].get("src")
res=requests.get(photoUrl)
res.raise_for_status
print ("Do you want to save it? (y/n)")
ans=input()
if ans=="y":
name=input("How to name it?")
fileName=name+".jpg"
fileNames.append(fileName)
imageFile=open(os.path.join("wallpapers",fileName),"wb")
print ("Saving " + fileName + " to the hard drive")
for chunk in res.iter_content(100000):
imageFile.write(chunk)
imageFile.close()
imagesSaved += 1
i+=1
continue
elif ans=="n":
i+=1
continue
else:
print("Tell me if you want to save it (y/n)")
except requests.exceptions.ConnectionError:
print("Connection refused by the server..")
time.sleep(5)
continue
但是当我打开前三张图片时,循环再次打开它们(第四张图片与第一张相同,第五张与第二张相同,依此类推)。它每次都会发生,具有不同的图像类别,我要保存的图像数量不同。为什么会发生,为什么前三个总是重复?
【问题讨论】:
-
这就是一个脚本吧?只是中间有评论?
-
elemLinks是否包含您期望的不同对象,没有重复?
标签: python beautifulsoup