how to download multiple googel images using python

Solutions on MaxInterview for how to download multiple googel images using python by the best coders in the world

showing results for - "how to download multiple googel images using python"
Yannic
13 Oct 2017
1from bs4 import BeautifulSoup
2import requests
3import re
4import urllib2
5import os
6import cookielib
7import json
8
9def get_soup(url,header):
10    return BeautifulSoup(urllib2.urlopen(urllib2.Request(url,headers=header)),'html.parser')
11
12
13query = raw_input("query image")# you can change the query for the image  here
14image_type="ActiOn"
15query= query.split()
16query='+'.join(query)
17url="https://www.google.co.in/search?q="+query+"&source=lnms&tbm=isch"
18print url
19#add the directory for your image here
20DIR="Pictures"
21header={'User-Agent':"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.134 Safari/537.36"
22}
23soup = get_soup(url,header)
24
25
26ActualImages=[]# contains the link for Large original images, type of  image
27for a in soup.find_all("div",{"class":"rg_meta"}):
28    link , Type =json.loads(a.text)["ou"]  ,json.loads(a.text)["ity"]
29    ActualImages.append((link,Type))
30
31print  "there are total" , len(ActualImages),"images"
32
33if not os.path.exists(DIR):
34            os.mkdir(DIR)
35DIR = os.path.join(DIR, query.split()[0])
36
37if not os.path.exists(DIR):
38            os.mkdir(DIR)
39###print images
40for i , (img , Type) in enumerate( ActualImages):
41    try:
42        req = urllib2.Request(img, headers={'User-Agent' : header})
43        raw_img = urllib2.urlopen(req).read()
44
45        cntr = len([i for i in os.listdir(DIR) if image_type in i]) + 1
46        print cntr
47        if len(Type)==0:
48            f = open(os.path.join(DIR , image_type + "_"+ str(cntr)+".jpg"), 'wb')
49        else :
50            f = open(os.path.join(DIR , image_type + "_"+ str(cntr)+"."+Type), 'wb')
51
52
53        f.write(raw_img)
54        f.close()
55    except Exception as e:
56        print "could not load : "+img
57        print e
58
similar questions