-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathgoogle_image_search.py
144 lines (119 loc) · 5.37 KB
/
google_image_search.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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
#coding=utf-8
# Copyright (c) 2016 Kenneth Blomqvist
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
############################
## How to use
############################
# modify google file: the 1st column is the file path, and the 2nd column is the seaching key-word
# modify count, the param is the minimum searching result count.
# sometimes, the final searching number is small, eg. count=500, but only return 28. This may be related to the webdriver, it's a bug, but I don't know how to fix it. Run it again, it returns correctly.
import os
import re
import time
from selenium import webdriver
def ensure_directory(path):
if not os.path.exists(path):
os.mkdir(path)
def largest_file(dir_path):
def parse_num(filename):
match = re.search('\d+', filename)
if match:
return int(match.group(0))
files = os.listdir(dir_path)
if len(files) != 0:
return max(filter(lambda x: x, map(parse_num, files)))
else:
return 0
def fetch_image_urls_google(query, images_to_download):
image_urls = set()
search_url = "https://www.google.com/search?safe=off&site=&tbm=isch&source=hp&q={q}&oq={q}&gs_l=img"
# browser = webdriver.Firefox()
browser = webdriver.Chrome()
browser.get(search_url.format(q=query))
def scroll_to_bottom():
browser.execute_script("window.scrollTo(0, document.body.scrollHeight);")
time.sleep(10)
image_count = len(image_urls)
delta = 0
while image_count < images_to_download:
print("Found:", len(image_urls), "plant_disease")
scroll_to_bottom()
images = browser.find_elements_by_css_selector("img.rg_ic")
for img in images:
image_urls.add(img.get_attribute('src'))
delta = len(image_urls) - image_count
image_count = len(image_urls)
if delta == 0:
print("Can't find more plant_disease")
break
fetch_more_button = browser.find_element_by_css_selector(".ksb._kvc")
if fetch_more_button:
browser.execute_script("document.querySelector('.ksb._kvc').click();")
scroll_to_bottom()
browser.quit()
return image_urls
def fetch_image_urls_soso(query, images_to_download):
image_urls = set()
search_url = "http://pic.sogou.com/pics?query={q}&di=2&_asf=pic.sogou.com&w=05009900"
# browser = webdriver.Firefox()
browser = webdriver.Chrome()
browser.get(search_url.format(q=query))
def scroll_to_bottom():
browser.execute_script("window.scrollTo(0, document.body.scrollHeight);")
time.sleep(5)
image_count = len(image_urls)
delta = 0
while image_count < images_to_download:
print("Found:", len(image_urls), "plant_disease")
scroll_to_bottom()
images = browser.find_elements_by_xpath('//div[@id="imgid"]/ul/li/a/img')
for img in images:
image_urls.add(img.get_attribute('src'))
delta = len(image_urls) - image_count
image_count = len(image_urls)
if delta == 0:
print("Can't find more plant_disease")
break
browser.quit()
return image_urls
if __name__ == '__main__':
count = 100
is_google = True
savepath = os.path.abspath('./image/')
query = []
label = []
with open('./google') as f:
lines = f.readlines()
for line in lines:
re = line.strip().split('\t')
query.append(re[1])
label.append(re[0])
f.close()
ensure_directory(savepath)
for i, val in enumerate(query):
query_directory = savepath + "/"+ label[i] + "/"
ensure_directory(query_directory)
if is_google:
image_urls = fetch_image_urls_google(val, count)
else:
image_urls = fetch_image_urls_soso(val, count)
print("image count", len(image_urls))
cnt = 0
os.chdir(os.path.abspath(query_directory))
for url in image_urls:
if url is None:
continue
# print url
if is_google:
curl = 'curl -o ' + '\'%s_%04d.jpg\'' % (
label[i], cnt) + ' --connect-timeout 40 -m 80 --insecure ' + '\''+url+'\'' + ' --socks5-hostname 127.0.0.1:1080\n'
else:
curl = 'curl -o ' + '\'%s_%04d.jpg\'' % (
label[i], cnt) + ' --connect-timeout 40 -m 80 --insecure ' + '\'' + url + '\'\n'
os.system(curl)
cnt += 1