-
Notifications
You must be signed in to change notification settings - Fork 0
/
image_scraper.py
70 lines (51 loc) · 1.95 KB
/
image_scraper.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
67
68
69
70
from selenium import webdriver
from selenium.webdriver.common.by import By
import requests
import io
from PIL import Image
import time
PATH = "C:\\Py Projects\\Machine Learning\\Functional Group Detector\\chromedriver.exe"
wd = webdriver.Chrome(PATH)
def get_images_from_google(wd, delay, max_images):
def scroll_down(wd):
wd.execute_script("window.scrollTo(0, document.body.scrollHeight);")
time.sleep(delay)
url = "https://www.google.com/search?q=randomorganic+compounds&tbm=isch&ved=2ahUKEwit2a2OlZ38AhX-CUQIHXZxD0MQ2-cCegQIABAA&oq=randomorganic+compounds&gs_lcp=CgNpbWcQAzoECAAQQzoFCAAQgARQ_QFYnhRg1xVoAHAAeAGAAdMNiAHKH5IBCTIuMi4xLjgtMpgBAKABAaoBC2d3cy13aXotaW1nwAEB&sclient=img&ei=vaisY-2GNv6TkPIP9uK9mAQ"
wd.get(url)
image_urls = set()
skips = 0
while len(image_urls) + skips < max_images:
scroll_down(wd)
thumbnails = wd.find_elements(By.CLASS_NAME, "Q4LuWd")
for img in thumbnails[len(image_urls) + skips:max_images]:
try:
img.click()
time.sleep(delay)
except:
continue
images = wd.find_elements(By.CLASS_NAME, "n3VNCb")
for image in images:
if image.get_attribute('src') in image_urls:
max_images += 1
skips += 1
break
if image.get_attribute('src') and 'http' in image.get_attribute('src'):
image_urls.add(image.get_attribute('src'))
print(f"Found {len(image_urls)}")
return image_urls
def download_image(download_path, url, file_name):
try:
image_content = requests.get(url).content
image_file = io.BytesIO(image_content)
image = Image.open(image_file)
file_path = download_path + file_name
with open(file_path, "wb") as f:
image.save(f, "PNG")
print("Success")
except Exception as e:
print('FAILED -', e)
urls = get_images_from_google(wd, 1, 5)
print (urls)
for i, link in enumerate(urls):
download_image("C:\\Py Projects\\Machine Learning\\test_images\\", link, str(i+5) +".png")
wd.quit()