-
Notifications
You must be signed in to change notification settings - Fork 0
/
dd.py
66 lines (45 loc) · 1.58 KB
/
dd.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# First Section: Importing Libraries
import os
import requests
from bs4 import BeautifulSoup
# Second Section: Declare important variables
google_image = "https://www.google.com/search?site=&tbm=isch&source=hp&biw=1873&bih=990&"
user_agent = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36"
}
# Third Section: Build the main function
saved_folder = 'images'
def main():
if not os.path.exists(saved_folder):
os.mkdir(saved_folder)
download_images()
# Fourth Section: Build the download function
def download_images():
data = input('What are you looking for? ')
n_images = int(input('How many images do you want? '))
print('searching...')
search_url = google_image + 'q=' + data
response = requests.get(search_url, headers=user_agent)
html = response.text
soup = BeautifulSoup(html, 'html.parser')
results = soup.findAll('img', {'class': 'rg_i Q4LuWd'})
count = 1
links = []
for result in results:
try:
link = result['data-src']
links.append(link)
count += 1
if(count > n_images):
break
except KeyError:
continue
print(f"Downloading {len(links)} images...")
for i, link in enumerate(links):
response = requests.get(link)
image_name = saved_folder + '/' + data + str(i+1) + '.jpg'
with open(image_name, 'wb') as fh:
fh.write(response.content)
# Fifth Section: Run your code
if __name__ == "__main__":
main()