Issue
# libraries
import os
import urllib.request as ureq
from bs4 import BeautifulSoup
import requests
# neccesary things
save_folder="Images"
#img_links=[]
usr_agent={"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36"}
g_img="https://www.google.com/search?site=&tbm=isch&source=hp&biw=1873&bih=990&"
# Save folder
def folder():
if not os.path.exists(save_folder):
os.mkdir(save_folder)
# get_links
def get_links(data,number):
img_links=[]
searchurl=g_img+"q="+data
response=requests.get(searchurl,headers=usr_agent).text
soup=BeautifulSoup(response,"lxml")
# results=soup.find_all("a",attrs={"class":"VFACy"},limit=number)
results=soup.find_all("img", attrs={"class":"rg_i"},limit=number)
for result in results:
link=result.get("src")
img_links.append(link)
return img_links
# download_img
def download_img(data, links):
for i, link in enumerate(links):
img_name=save_folder+"/"+data+"{:06}.jpg".format(i)
ureq.urlretrieve(link,img_name)
# main
def main(data,n_img):
folder()
link=get_links(data,n_img)
download_img(data, link)
# Run
if __name__=="__main__":
data=input("What are you looking for?\nData:")
n_img=int(input("How many do you want?\nNumber:"))
main(data,n_img)
Solution
Let's try this:
def download_img(data, links):
for i, link in enumerate(links):
img_name=save_folder+"/"+data+"{:06}.jpg".format(i)
images = requests.get(link)
with open(img_name, 'wb') as writer:
writer.write(images.content)
And some variable names are defined out of scope
Answered By - Dratius
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.