0
votes
# 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)
1
I want to download image, And I wrote above code. This code download image but, there is nothing inside of image. Where is my error.? Thank youdralioz
Welcome to SO! The statement of your question should be within the body of your post, instead of being in a comment. That way people can clearly find what you're asking for help with.Savage Henry

1 Answers

0
votes

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