-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathimagescraper.py
More file actions
40 lines (31 loc) · 1.01 KB
/
imagescraper.py
File metadata and controls
40 lines (31 loc) · 1.01 KB
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
from PIL import Image
from bs4 import BeautifulSoup
from io import BytesIO
import requests as r
import os
def start_search():
search = input('Search: ')
params = {'q': search}
dir_name = search.replace(" ", "_").lower()
try:
if not os.path.isdir(dir_name):
os.makedirs(dir_name)
except IOError:
print("can't create a folder")
data = r.get('http://www.bing.com/images/search', params=params)
soup = BeautifulSoup(data.text, 'html.parser')
links = soup.findAll('a', {'class': 'thumb'})
for item in links:
try:
img_obj = r.get(item.attrs['href'])
print('Getting..', item.attrs['href'])
title = item.attrs['href'].split('/')[-1]
try:
img = Image.open(BytesIO(img_obj.content))
img.save('./Scraped_Images/' + title, img.format)
except:
print('Could not save image!')
except:
print('Server error!')
start_search()
start_search()