-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcollect_links.py
167 lines (132 loc) · 6.18 KB
/
collect_links.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
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
import time
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.common.exceptions import ElementNotVisibleException, StaleElementReferenceException
import platform
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.chrome.options import Options
from webdriver_manager.chrome import ChromeDriverManager
import os.path as osp
class CollectLinks:
def __init__(self, no_gui=False, proxy=None, print_url=False):
self.print_url = print_url
executable = ''
if platform.system() == 'Windows':
print('Detected OS : Windows')
executable = './chromedriver/chromedriver_win.exe'
elif platform.system() == 'Linux':
print('Detected OS : Linux')
executable = './chromedriver/chromedriver_linux'
elif platform.system() == 'Darwin':
print('Detected OS : Mac')
executable = './chromedriver/chromedriver_mac'
else:
raise OSError('Unknown OS Type')
if not osp.exists(executable):
raise FileNotFoundError('Chromedriver file should be placed at {}'.format(executable))
chrome_options = Options()
chrome_options.add_argument('--no-sandbox')
chrome_options.add_argument('--disable-dev-shm-usage')
if no_gui:
chrome_options.add_argument('--headless')
if proxy:
chrome_options.add_argument("--proxy-server={}".format(proxy))
self.browser = webdriver.Chrome(executable, chrome_options=chrome_options)
browser_version = 'Failed to detect version'
chromedriver_version = 'Failed to detect version'
major_version_different = False
if 'browserVersion' in self.browser.capabilities:
browser_version = str(self.browser.capabilities['browserVersion'])
if 'chrome' in self.browser.capabilities:
if 'chromedriverVersion' in self.browser.capabilities['chrome']:
chromedriver_version = str(self.browser.capabilities['chrome']['chromedriverVersion']).split(' ')[0]
if browser_version.split('.')[0] != chromedriver_version.split('.')[0]:
major_version_different = True
print('_________________________________')
print('Current web-browser version:\t{}'.format(browser_version))
print('Current chrome-driver version:\t{}'.format(chromedriver_version))
if major_version_different:
print('warning: Version different')
print(
'Download correct version at "http://chromedriver.chromium.org/downloads" and place in "./chromedriver"')
print('_________________________________')
def get_scroll(self):
pos = self.browser.execute_script("return window.pageYOffset;")
return pos
def wait_and_click(self, xpath):
# Sometimes click fails unreasonably. So tries to click at all cost.
try:
w = WebDriverWait(self.browser, 15)
elem = w.until(EC.element_to_be_clickable((By.XPATH, xpath)))
elem.click()
self.highlight(elem)
except Exception as e:
print('Click time out - {}'.format(xpath))
print('Refreshing browser...')
self.browser.refresh()
time.sleep(2)
return self.wait_and_click(xpath)
return elem
def highlight(self, element):
self.browser.execute_script("arguments[0].setAttribute('style', arguments[1]);", element,
"background: yellow; border: 2px solid red;")
def google_full(self, keyword, add_url=""):
if osp.exists(osp.join("./collected_links", keyword+".txt")):
return []
print('[Full Resolution Mode]')
self.browser.get("https://www.google.com/search?q={}&tbm=isch{}".format(keyword, add_url))
time.sleep(1)
elem = self.browser.find_element_by_tag_name("body")
print('Scraping links')
self.wait_and_click('//div[@data-ri="0"]')
time.sleep(1)
links = []
count = 1
last_scroll = 0
scroll_patience = 0
while True:
try:
xpath = '//div[@id="islsp"]//div[@class="v4dQwb"]'
div_box = self.browser.find_element(By.XPATH, xpath)
self.highlight(div_box)
xpath = '//img[@class="n3VNCb"]'
img = div_box.find_element(By.XPATH, xpath)
self.highlight(img)
xpath = '//div[@class="k7O2sd"]'
loading_bar = div_box.find_element(By.XPATH, xpath)
# Wait for image to load. If not it will display base64 code.
while str(loading_bar.get_attribute('style')) != 'display: none;':
time.sleep(0.5)
src = img.get_attribute('src')
if src is not None:
links.append(src)
if self.print_url:
print('%d: %s' % (count, src))
else:
print('%s: %d' % (keyword, count))
count += 1
with open(osp.join("./collected_links", keyword+".txt"), "a+") as f_save:
f_save.write(src+"\n")
except StaleElementReferenceException:
# print('[Expected Exception - StaleElementReferenceException]')
pass
except Exception as e:
print('[Exception occurred while collecting links from google_full] {}'.format(e))
scroll = self.get_scroll()
if scroll == last_scroll:
scroll_patience += 1
else:
scroll_patience = 0
last_scroll = scroll
if scroll_patience >= 30:
break
elem.send_keys(Keys.RIGHT)
print('Collect links done. Site: {}, Keyword: {}, Total: {}'.format('google_full', keyword, len(links)))
self.browser.close()
return links
if __name__ == '__main__':
collect = CollectLinks()
links = collect.google_full('tennis')
print(len(links), links)