-
Notifications
You must be signed in to change notification settings - Fork 6
/
lksn_search_scraper.py
330 lines (282 loc) · 11.2 KB
/
lksn_search_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
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
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
"""
This is meant to be run as a CLI script.
It will scrap the search results of a LinkedIn Sales Navigator search.
Example usage:
python lksn_search_scraper.py --search-url "https://www.linkedin.com/sales/search/people?query=(spellCorrectionEnabled%3Atrue%2Ckeywords%3Ascraping)"
"""
import argparse
import os
import logging
from bs4 import BeautifulSoup
from tqdm import tqdm
import time
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import pandas as pd
from general_lk_utils import (
remove_url_parameter,
get_lk_credentials,
enter_ids_on_lk_signin,
get_lk_url_from_sales_lk_url,
)
SCROLL_TO_BOTTOM_COMMAND = (
"document.getElementById('search-results-container').scrollTop+=100000;"
)
LK_CREDENTIALS_PATH = "./lk_credentials.json"
def get_name_info_from_result_el(result_el):
selector = "div > div > div.flex.justify-space-between.full-width > div.flex.flex-column > div.mb3 > div > div.artdeco-entity-lockup__content.ember-view > div.flex.flex-wrap.align-items-center > div.artdeco-entity-lockup__title.ember-view > a"
els = result_el.select(selector)
link_to_profile = ""
name = ""
if len(els) > 0:
link_to_profile = els[0]["href"]
el_contents = els[0].contents
if len(el_contents) > 0:
name = el_contents[0].strip()
return {"name": name, "link_to_profile": link_to_profile}
def get_connection_level_info_from_result_el(result_el):
selector = "div > div > div.flex.justify-space-between.full-width > div.flex.flex-column > div.mb3 > div > div.artdeco-entity-lockup__content.ember-view > div.flex.flex-wrap.align-items-center > div.artdeco-entity-lockup__badge.ember-view.ml1 > span.artdeco-entity-lockup__degree"
els = result_el.select(selector)
connection_level = ""
if len(els) > 0:
link_to_profile = els[0]
el_contents = els[0].contents
if len(el_contents) > 0:
connection_level = el_contents[0].strip().replace("·\xa0", "")
return {"connection_level": connection_level}
def get_search_url(search_url_base, page=1):
url = search_url_base + f"&page={page}"
return url
def get_linkedin_premium_info_from_result_el(result_el):
selector = "div > div > div.flex.justify-space-between.full-width > div.flex.flex-column > div.mb3 > div > div.artdeco-entity-lockup__content.ember-view > div.inline-flex > div > li-icon"
els = result_el.select(selector)
has_linkedin_premium = False
if len(els) > 0:
has_linkedin_premium = True
return {"has_linkedin_premium": has_linkedin_premium}
def get_role_info_from_result_el(result_el):
selector = "div > div > div.flex.justify-space-between.full-width > div.flex.flex-column > div.mb3 > div > div.artdeco-entity-lockup__content.ember-view > div.artdeco-entity-lockup__subtitle.ember-view.t-14 > span"
els = result_el.select(selector)
role_name = ""
if len(els) > 0:
el_contents = els[0].contents
if len(el_contents) > 0:
role_name = el_contents[0].strip()
return {"role_name": role_name}
def get_company_info_from_result_el(result_el):
selector = "div > div > div.flex.justify-space-between.full-width > div.flex.flex-column > div.mb3 > div > div.artdeco-entity-lockup__content.ember-view > div.artdeco-entity-lockup__subtitle.ember-view.t-14 > a"
els = result_el.select(selector)
link_to_company = ""
company_name = ""
if len(els) > 0:
link_to_company = els[0]["href"]
el_contents = els[0].contents
if len(el_contents) > 0:
company_name = el_contents[0].strip()
return {"link_to_company": link_to_company, "company_name": company_name}
def get_time_in_company_info_from_result_el(result_el):
selector = "div > div > div.flex.justify-space-between.full-width > div.flex.flex-column > div.mb3 > div > div.artdeco-entity-lockup__content.ember-view > div.artdeco-entity-lockup__metadata.ember-view"
els = result_el.select(selector)
time_in_company = ""
if len(els) > 0:
el_contents = els[0].contents
if len(el_contents) > 0:
time_in_company = " | ".join(
[
el_contents[i].strip().replace("\xa0", " ")
for i in range(len(el_contents))
if "<span" not in str(el_contents[i])
]
)
return {"time_in_company": time_in_company}
def get_additional_info_from_result_el(result_el):
selector = "div > div > div.flex.justify-space-between.full-width > div.flex.flex-column > div.ml8.pl1 > dl > div > dd > div > span"
els = result_el.select(selector)
additional_info = ""
if len(els) > 1:
el_contents = els[1].contents
if len(el_contents) > 0:
additional_info = " | ".join(
[
el_contents[i].strip().replace("\xa0", " ")
for i in range(len(el_contents))
if "<span" not in str(el_contents[i])
and "<button" not in str(el_contents[i])
]
)
return {"additional_info": additional_info}
def get_info_from_result_el(result_el):
r = []
r.append(get_name_info_from_result_el(result_el))
r.append(get_connection_level_info_from_result_el(result_el))
r.append(get_linkedin_premium_info_from_result_el(result_el))
r.append(get_role_info_from_result_el(result_el))
r.append(get_company_info_from_result_el(result_el))
r.append(get_time_in_company_info_from_result_el(result_el))
r.append(get_additional_info_from_result_el(result_el))
info = {}
for obj in r:
for k in obj.keys():
info[k] = obj[k]
info["time_scraped"] = int(time.time() * 1000)
return info
def get_result_els(page_source):
soup = BeautifulSoup(page_source, "html.parser")
full_results_selector = "#search-results-container > div > ol > li"
all_results_el = soup.select(full_results_selector)
return all_results_el
def get_all_info_from_page_source(page_source):
print("Getting all result elements...")
result_els = get_result_els(page_source)
n = len(result_els)
print(f"Found {n} elements.")
print("Getting the info for all elements...")
infos = []
for i in tqdm(range(n)):
new_info = get_info_from_result_el(result_els[i])
infos.append(new_info)
return infos
def get_all_info_from_search_url(
driver, url, wait_after_page_loaded=3, wait_after_scroll_down=2
):
driver.get(url)
print(f"Waiting for {wait_after_page_loaded}s...")
time.sleep(wait_after_page_loaded)
# Chrome must be unzoomed so that the whole page fits in the screen in 2 times
try:
driver.execute_script(SCROLL_TO_BOTTOM_COMMAND)
except:
print("There was an error scrolling down")
print(f"Waiting for {wait_after_scroll_down}s...")
time.sleep(wait_after_scroll_down)
page_source = driver.page_source
page_parsed_info = get_all_info_from_page_source(page_source)
return page_parsed_info
def scrap_lksn_pages(
driver,
page_list,
get_search_url,
wait_time_between_pages=3,
wait_after_page_loaded=3,
wait_after_scroll_down=2,
):
total_info = []
for p in page_list:
print(f"Waiting for {wait_time_between_pages}s...")
time.sleep(wait_time_between_pages)
print(f"Getting new page: {p}.")
info = get_all_info_from_search_url(
driver,
get_search_url(p),
wait_after_page_loaded=wait_after_page_loaded,
wait_after_scroll_down=wait_after_scroll_down,
)
total_info += info
return total_info
if __name__ == "__main__":
# Parse the arguments
parser = argparse.ArgumentParser(description="Scrap LinkedIn Sales Navigator")
parser.add_argument(
"--search-url",
type=str,
help="The url of the search page to scrap",
required=True,
)
parser.add_argument(
"--start-page",
type=int,
help="The page to start scrapping from",
required=False,
default=1,
)
parser.add_argument(
"--end-page",
type=int,
help="The page to end scrapping at",
required=False,
default=1,
)
parser.add_argument(
"--wait-time-between-pages",
type=int,
help="The time in seconds to wait between pages",
required=False,
default=5,
)
parser.add_argument(
"--wait-after-page-loaded",
type=int,
help="The time in seconds to wait after the page is loaded",
required=False,
default=3,
)
parser.add_argument(
"--wait-after-scroll-down",
type=int,
help="The time in seconds to wait after scrolling down",
required=False,
default=3,
)
parser.add_argument(
"--save-format",
type=str,
help="The format to save the data in (xlsx or csv)",
required=False,
default="csv",
)
args = parser.parse_args()
# Get the arguments
search_url = args.search_url
start_page = args.start_page
end_page = args.end_page
wait_time_between_pages = args.wait_time_between_pages
wait_after_page_loaded = args.wait_after_page_loaded
wait_after_scroll_down = args.wait_after_scroll_down
save_format = args.save_format
search_url_base = remove_url_parameter(search_url, "page")
print("Starting the driver...")
logging.getLogger("selenium").setLevel(logging.CRITICAL)
# Start the webdriver without any logs
driver = webdriver.Chrome(options=Options())
driver.maximize_window()
driver.get("https://www.linkedin.com/login/")
print("Inputting the credentials...")
lk_credentials = get_lk_credentials(LK_CREDENTIALS_PATH)
enter_ids_on_lk_signin(driver, lk_credentials["email"], lk_credentials["password"])
if "checkpoint/challenge" in driver.current_url:
print(
"It looks like you need to complete a double factor authentification. Please do so and press enter when you are done."
)
input()
driver.get(search_url)
print(
"Manual actions needed: go to the browser window and unzoom the page so that the whole page fits in the screen in 2 times. Then press enter here."
)
input()
print("Starting the scraping...")
lksnSearchInfos = scrap_lksn_pages(
driver,
page_list=range(start_page, end_page + 1),
get_search_url=lambda x: get_search_url(search_url_base, x),
wait_time_between_pages=wait_time_between_pages,
wait_after_page_loaded=wait_after_page_loaded,
wait_after_scroll_down=wait_after_scroll_down,
)
df = pd.DataFrame(lksnSearchInfos)
df["linkedin_url"] = df.link_to_profile.apply(get_lk_url_from_sales_lk_url)
if save_format == "csv":
file_name = f"{str(int(time.time()*1000))}_lk_salesnav_export.csv"
df.to_csv(
f"./lksn_data/{file_name}",
index=False,
)
print(f"Saved to ./lksn_data/{file_name}")
else:
# save_format=="xlsx"
file_name = f"{str(int(time.time()*1000))}_lk_salesnav_export.xlsx"
df.to_excel(
f"./lksn_data/{file_name}",
index=False,
)
print(f"Saved to ./lksn_data/{file_name}")
driver.close()