#!/usr/bin/env python3
import os, bs4, sys, requests
try:
os.mkdir('Downloaded_Images')
except FileExistsError:
print('Saving files to Downloaded_Images folder')
for i in range(50):
# What to search
url_part_1 = "https://www.google.com/search?safe=strict&hl=en&site=imghp&tbm=isch&source=hp&biw$
url_part_2 = "#imgrc=Ek3sgIvXh3zzZM%3A"
image_to_search = sys.argv[1]
search = url_part_1 + image_to_search + url_part_2
# Issue GET request and download search page
responce = requests.get(search)
responce.raise_for_status()
soup = bs4.BeautifulSoup(responce.text, "html.parser")
# Locate the images
picture_element = soup.select('a img')
if picture_element == []:
print('Could not locate images something went wrong')
else:
picture_location = picture_element[i].get('src')
print('Downloading ' + str(i))
responce = requests.get(picture_location)
responce.raise_for_status()
image_file = open(os.path.join('Downloaded_Images', os.path.basename('image_' + str(i))$
for chunk in responce.iter_content(100000):
image_file.write(chunk)
image_file.close()
以下是我运行它的代码./google_images_downloader.py what_you_wanna_search。但是,如果你注意到它在范围内表示我(50)。这是问题,它不下载50个图像只有19.它只下载19无论搜索。我究竟做错了什么?我收到了错误
picture_location = picture_element [i] .get(' src') IndexError:列表索引超出范围
但是当我检查元素时,它看起来像picture_element = soup.select('一个img')是对的。谢谢你的帮助!