-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathlinkedin.py
1527 lines (1286 loc) · 54 KB
/
linkedin.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
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Provides linkedin api-related code
"""
import base64
import json
import logging
import random
import uuid
from operator import itemgetter
from time import sleep, time
from urllib.parse import quote, urlencode
from linkedin_api.client import Client
from linkedin_api.utils.helpers import (
append_update_post_field_to_posts_list,
get_id_from_urn,
get_urn_from_raw_update,
get_list_posts_sorted_without_promoted,
get_update_author_name,
get_update_author_profile,
get_update_content,
get_update_old,
get_update_url,
parse_list_raw_posts,
parse_list_raw_urns,
generate_trackingId,
generate_trackingId_as_charString,
)
logger = logging.getLogger(__name__)
def default_evade():
"""
A catch-all method to try and evade suspension from Linkedin.
Currenly, just delays the request by a random (bounded) time
"""
sleep(random.randint(2, 5)) # sleep a random duration to try and evade suspention
class Linkedin(object):
"""
Class for accessing the LinkedIn API.
:param username: Username of LinkedIn account.
:type username: str
:param password: Password of LinkedIn account.
:type password: str
"""
_MAX_POST_COUNT = 100 # max seems to be 100 posts per page
_MAX_UPDATE_COUNT = 100 # max seems to be 100
_MAX_SEARCH_COUNT = 49 # max seems to be 49, and min seems to be 2
_MAX_REPEATED_REQUESTS = (
200 # VERY conservative max requests count to avoid rate-limit
)
def __init__(
self,
username,
password,
*,
authenticate=True,
refresh_cookies=False,
debug=False,
proxies={},
cookies=None,
cookies_dir=None,
):
"""Constructor method"""
self.client = Client(
refresh_cookies=refresh_cookies,
debug=debug,
proxies=proxies,
cookies_dir=cookies_dir,
)
logging.basicConfig(level=logging.DEBUG if debug else logging.INFO)
self.logger = logger
if authenticate:
if cookies:
# If the cookies are expired, the API won't work anymore since
# `username` and `password` are not used at all in this case.
self.client._set_session_cookies(cookies)
else:
self.client.authenticate(username, password)
def _fetch(self, uri, evade=default_evade, base_request=False, **kwargs):
"""GET request to Linkedin API"""
evade()
url = f"{self.client.API_BASE_URL if not base_request else self.client.LINKEDIN_BASE_URL}{uri}"
return self.client.session.get(url, **kwargs)
def _post(self, uri, evade=default_evade, base_request=False, **kwargs):
"""POST request to Linkedin API"""
evade()
url = f"{self.client.API_BASE_URL if not base_request else self.client.LINKEDIN_BASE_URL}{uri}"
return self.client.session.post(url, **kwargs)
def get_profile_posts(self, public_id=None, urn_id=None, post_count=10):
"""
get_profile_posts: Get profile posts
:param public_id: LinkedIn public ID for a profile
:type public_id: str, optional
:param urn_id: LinkedIn URN ID for a profile
:type urn_id: str, optional
:param post_count: Number of posts to fetch
:type post_count: int, optional
:return: List of posts
:rtype: list
"""
url_params = {
"count": min(post_count, self._MAX_POST_COUNT),
"start": 0,
"q": "memberShareFeed",
"moduleKey": "member-shares:phone",
"includeLongTermHistory": True,
}
if urn_id:
profile_urn = f"urn:li:fsd_profile:{urn_id}"
else:
profile = self.get_profile(public_id=public_id)
profile_urn = profile["profile_urn"].replace(
"fs_miniProfile", "fsd_profile"
)
url_params["profileUrn"] = profile_urn
url = f"/identity/profileUpdatesV2"
res = self._fetch(url, params=url_params)
data = res.json()
if data and "status" in data and data["status"] != 200:
self.logger.info("request failed: {}".format(data["message"]))
return {}
while data and data["metadata"]["paginationToken"] != "":
if len(data["elements"]) >= post_count:
break
pagination_token = data["metadata"]["paginationToken"]
url_params["start"] = url_params["start"] + self._MAX_POST_COUNT
url_params["paginationToken"] = pagination_token
res = self._fetch(url, params=url_params)
data["metadata"] = res.json()["metadata"]
data["elements"] = data["elements"] + res.json()["elements"]
data["paging"] = res.json()["paging"]
return data["elements"]
def get_post_comments(self, post_urn, comment_count=100):
"""
get_post_comments: Get post comments
:param post_urn: Post URN
:type post_urn: str
:param comment_count: Number of comments to fetch
:type comment_count: int, optional
:return: List of post comments
:rtype: list
"""
url_params = {
"count": min(comment_count, self._MAX_POST_COUNT),
"start": 0,
"q": "comments",
"sortOrder": "RELEVANCE",
}
url = f"/feed/comments"
url_params["updateId"] = "activity:" + post_urn
res = self._fetch(url, params=url_params)
data = res.json()
if data and "status" in data and data["status"] != 200:
self.logger.info("request failed: {}".format(data["status"]))
return {}
while data and data["metadata"]["paginationToken"] != "":
if len(data["elements"]) >= comment_count:
break
pagination_token = data["metadata"]["paginationToken"]
url_params["start"] = url_params["start"] + self._MAX_POST_COUNT
url_params["count"] = self._MAX_POST_COUNT
url_params["paginationToken"] = pagination_token
res = self._fetch(url, params=url_params)
if res.json() and "status" in res.json() and res.json()["status"] != 200:
self.logger.info("request failed: {}".format(data["status"]))
return {}
data["metadata"] = res.json()["metadata"]
""" When the number of comments exceed total available
comments, the api starts returning an empty list of elements"""
if res.json()["elements"] and len(res.json()["elements"]) == 0:
break
if data["elements"] and len(res.json()["elements"]) == 0:
break
data["elements"] = data["elements"] + res.json()["elements"]
data["paging"] = res.json()["paging"]
return data["elements"]
def search(self, params, limit=-1, offset=0):
"""Perform a LinkedIn search.
:param params: Search parameters (see code)
:type params: dict
:param limit: Maximum length of the returned list, defaults to -1 (no limit)
:type limit: int, optional
:param offset: Index to start searching from
:type offset: int, optional
:return: List of search results
:rtype: list
"""
count = Linkedin._MAX_SEARCH_COUNT
if limit is None:
limit = -1
results = []
while True:
# when we're close to the limit, only fetch what we need to
if limit > -1 and limit - len(results) < count:
count = limit - len(results)
default_params = {
"count": str(count),
"filters": "List()",
"origin": "GLOBAL_SEARCH_HEADER",
"q": "all",
"start": len(results) + offset,
"queryContext": "List(spellCorrectionEnabled->true,relatedSearchesEnabled->true,kcardTypes->PROFILE|COMPANY)",
}
default_params.update(params)
keywords = (
f"keywords:{default_params['keywords']},"
if "keywords" in default_params
else ""
)
res = self._fetch(
f"/graphql?variables=(start:{default_params['start']},origin:{default_params['origin']},"
f"query:("
f"{keywords}"
f"flagshipSearchIntent:SEARCH_SRP,"
f"queryParameters:{default_params['filters']},"
f"includeFiltersInResponse:false))&=&queryId=voyagerSearchDashClusters"
f".b0928897b71bd00a5a7291755dcd64f0"
)
data = res.json()
data_clusters = data.get("data", []).get("searchDashClustersByAll", [])
if not data_clusters:
return []
if (
not data_clusters.get("_type", [])
== "com.linkedin.restli.common.CollectionResponse"
):
return []
new_elements = []
for it in data_clusters.get("elements", []):
if (
not it.get("_type", [])
== "com.linkedin.voyager.dash.search.SearchClusterViewModel"
):
continue
for el in it.get("items", []):
if (
not el.get("_type", [])
== "com.linkedin.voyager.dash.search.SearchItem"
):
continue
e = el.get("item", []).get("entityResult", [])
if not e:
continue
if (
not e.get("_type", [])
== "com.linkedin.voyager.dash.search.EntityResultViewModel"
):
continue
new_elements.append(e)
results.extend(new_elements)
# break the loop if we're done searching
# NOTE: we could also check for the `total` returned in the response.
# This is in data["data"]["paging"]["total"]
if (
(-1 < limit <= len(results)) # if our results exceed set limit
or len(results) / count >= Linkedin._MAX_REPEATED_REQUESTS
) or len(new_elements) == 0:
break
self.logger.debug(f"results grew to {len(results)}")
return results
def search_people(
self,
keywords=None,
connection_of=None,
network_depths=None,
current_company=None,
past_companies=None,
nonprofit_interests=None,
profile_languages=None,
regions=None,
industries=None,
schools=None,
contact_interests=None,
service_categories=None,
include_private_profiles=False, # profiles without a public id, "Linkedin Member"
# Keywords filter
keyword_first_name=None,
keyword_last_name=None,
# `keyword_title` and `title` are the same. We kept `title` for backward compatibility. Please only use one of them.
keyword_title=None,
keyword_company=None,
keyword_school=None,
network_depth=None, # DEPRECATED - use network_depths
title=None, # DEPRECATED - use keyword_title
**kwargs,
):
"""Perform a LinkedIn search for people.
:param keywords: Keywords to search on
:type keywords: str, optional
:param current_company: A list of company URN IDs (str)
:type current_company: list, optional
:param past_companies: A list of company URN IDs (str)
:type past_companies: list, optional
:param regions: A list of geo URN IDs (str)
:type regions: list, optional
:param industries: A list of industry URN IDs (str)
:type industries: list, optional
:param schools: A list of school URN IDs (str)
:type schools: list, optional
:param profile_languages: A list of 2-letter language codes (str)
:type profile_languages: list, optional
:param contact_interests: A list containing one or both of "proBono" and "boardMember"
:type contact_interests: list, optional
:param service_categories: A list of service category URN IDs (str)
:type service_categories: list, optional
:param network_depth: Deprecated, use `network_depths`. One of "F", "S" and "O" (first, second and third+ respectively)
:type network_depth: str, optional
:param network_depths: A list containing one or many of "F", "S" and "O" (first, second and third+ respectively)
:type network_depths: list, optional
:param include_private_profiles: Include private profiles in search results. If False, only public profiles are included. Defaults to False
:type include_private_profiles: boolean, optional
:param keyword_first_name: First name
:type keyword_first_name: str, optional
:param keyword_last_name: Last name
:type keyword_last_name: str, optional
:param keyword_title: Job title
:type keyword_title: str, optional
:param keyword_company: Company name
:type keyword_company: str, optional
:param keyword_school: School name
:type keyword_school: str, optional
:param connection_of: Connection of LinkedIn user, given by profile URN ID
:type connection_of: str, optional
:return: List of profiles (minimal data only)
:rtype: list
"""
filters = ["(key:resultType,value:List(PEOPLE))"]
if connection_of:
filters.append(f"(key:connectionOf,value:List({connection_of}))")
if network_depths:
stringify = " | ".join(network_depths)
filters.append(f"(key:network,value:List({stringify}))")
elif network_depth:
filters.append(f"(key:network,value:List({network_depth}))")
if regions:
stringify = " | ".join(regions)
filters.append(f"(key:geoUrn,value:List({stringify}))")
if industries:
stringify = " | ".join(industries)
filters.append(f"(key:industry,value:List({stringify}))")
if current_company:
stringify = " | ".join(current_company)
filters.append(f"(key:currentCompany,value:List({stringify}))")
if past_companies:
stringify = " | ".join(past_companies)
filters.append(f"(key:pastCompany,value:List({stringify}))")
if profile_languages:
stringify = " | ".join(profile_languages)
filters.append(f"(key:profileLanguage,value:List({stringify}))")
if nonprofit_interests:
stringify = " | ".join(nonprofit_interests)
filters.append(f"(key:nonprofitInterest,value:List({stringify}))")
if schools:
stringify = " | ".join(schools)
filters.append(f"(key:schools,value:List({stringify}))")
if service_categories:
stringify = " | ".join(service_categories)
filters.append(f"(key:serviceCategory,value:List({stringify}))")
# `Keywords` filter
keyword_title = keyword_title if keyword_title else title
if keyword_first_name:
filters.append(f"(key:firstName,value:List({keyword_first_name}))")
if keyword_last_name:
filters.append(f"(key:lastName,value:List({keyword_last_name}))")
if keyword_title:
filters.append(f"(key:title,value:List({keyword_title}))")
if keyword_company:
filters.append(f"(key:company,value:List({keyword_company}))")
if keyword_school:
filters.append(f"(key:school,value:List({keyword_school}))")
params = {"filters": "List({})".format(",".join(filters))}
if keywords:
params["keywords"] = keywords
data = self.search(params, **kwargs)
results = []
for item in data:
if (
not include_private_profiles
and (item.get("entityCustomTrackingInfo") or {}).get(
"memberDistance", None
)
== "OUT_OF_NETWORK"
):
continue
results.append(
{
"urn_id": get_id_from_urn(
get_urn_from_raw_update(item.get("entityUrn", None))
),
"distance": (item.get("entityCustomTrackingInfo") or {}).get(
"memberDistance", None
),
"jobtitle": (item.get("primarySubtitle") or {}).get("text", None),
"location": (item.get("secondarySubtitle") or {}).get("text", None),
"name": (item.get("title") or {}).get("text", None),
}
)
return results
def search_companies(self, keywords=None, **kwargs):
"""Perform a LinkedIn search for companies.
:param keywords: A list of search keywords (str)
:type keywords: list, optional
:return: List of companies
:rtype: list
"""
filters = ["(key:resultType,value:List(COMPANIES))"]
params = {
"filters": "List({})".format(",".join(filters)),
"queryContext": "List(spellCorrectionEnabled->true)",
}
if keywords:
params["keywords"] = keywords
data = self.search(params, **kwargs)
results = []
for item in data:
if "company" not in item.get("trackingUrn"):
continue
results.append(
{
"urn_id": get_id_from_urn(item.get("trackingUrn", None)),
"name": (item.get("title") or {}).get("text", None),
"headline": (item.get("primarySubtitle") or {}).get("text", None),
"subline": (item.get("secondarySubtitle") or {}).get("text", None),
}
)
return results
def search_jobs(
self,
keywords=None,
companies=None,
experience=None,
job_type=None,
job_title=None,
industries=None,
location_name=None,
remote=None,
listed_at=24 * 60 * 60,
distance=None,
limit=-1,
offset=0,
**kwargs,
):
"""Perform a LinkedIn search for jobs.
:param keywords: Search keywords (str)
:type keywords: str, optional
:param companies: A list of company URN IDs (str)
:type companies: list, optional
:param experience: A list of experience levels, one or many of "1", "2", "3", "4", "5" and "6" (internship, entry level, associate, mid-senior level, director and executive, respectively)
:type experience: list, optional
:param job_type: A list of job types , one or many of "F", "C", "P", "T", "I", "V", "O" (full-time, contract, part-time, temporary, internship, volunteer and "other", respectively)
:type job_type: list, optional
:param job_title: A list of title URN IDs (str)
:type job_title: list, optional
:param industries: A list of industry URN IDs (str)
:type industries: list, optional
:param location_name: Name of the location to search within. Example: "Kyiv City, Ukraine"
:type location_name: str, optional
:param remote: Filter for remote jobs, onsite or hybrid. onsite:"1", remote:"2", hybrid:"3"
:type remote: list, optional
:param listed_at: maximum number of seconds passed since job posting. 86400 will filter job postings posted in last 24 hours.
:type listed_at: int/str, optional. Default value is equal to 24 hours.
:param distance: maximum distance from location in miles
:type distance: int/str, optional. If not specified, None or 0, the default value of 25 miles applied.
:param limit: maximum number of results obtained from API queries. -1 means maximum which is defined by constants and is equal to 1000 now.
:type limit: int, optional, default -1
:param offset: indicates how many search results shall be skipped
:type offset: int, optional
:return: List of jobs
:rtype: list
"""
count = Linkedin._MAX_SEARCH_COUNT
if limit is None:
limit = -1
query = {"origin":"JOB_SEARCH_PAGE_QUERY_EXPANSION"}
if keywords:
query["keywords"] = "KEYWORD_PLACEHOLDER"
if location_name:
query["locationFallback"] = "LOCATION_PLACEHOLDER"
# In selectedFilters()
query['selectedFilters'] = {}
if companies:
query['selectedFilters']['company'] = f"List({','.join(companies)})"
if experience:
query['selectedFilters']['experience'] = f"List({','.join(experience)})"
if job_type:
query['selectedFilters']['jobType'] = f"List({','.join(job_type)})"
if job_title:
query['selectedFilters']['title'] = f"List({','.join(job_title)})"
if industries:
query['selectedFilters']['industry'] = f"List({','.join(industries)})"
if distance:
query['selectedFilters']['distance'] = f"List({distance})"
if remote:
query['selectedFilters']['workplaceType'] = f"List({','.join(remote)})"
query['selectedFilters']['timePostedRange'] = f"List(r{listed_at})"
query["spellCorrectionEnabled"] = "true"
# Query structure:
# "(
# origin:JOB_SEARCH_PAGE_QUERY_EXPANSION,
# keywords:marketing%20manager,
# locationFallback:germany,
# selectedFilters:(
# distance:List(25),
# company:List(163253),
# salaryBucketV2:List(5),
# timePostedRange:List(r2592000),
# workplaceType:List(1)
# ),
# spellCorrectionEnabled:true
# )"
query = str(query).replace(" ","") \
.replace("'","") \
.replace("KEYWORD_PLACEHOLDER", keywords or "") \
.replace("LOCATION_PLACEHOLDER", location_name or "") \
.replace("{","(") \
.replace("}",")")
results = []
while True:
# when we're close to the limit, only fetch what we need to
if limit > -1 and limit - len(results) < count:
count = limit - len(results)
default_params = {
"decorationId": "com.linkedin.voyager.dash.deco.jobs.search.JobSearchCardsCollection-174",
"count": count,
"q": "jobSearch",
"query": query,
"start": len(results) + offset,
}
res = self._fetch(
f"/voyagerJobsDashJobCards?{urlencode(default_params, safe='(),:')}",
headers={"accept": "application/vnd.linkedin.normalized+json+2.1"},
)
data = res.json()
elements = data.get("included", [])
new_data = [
i
for i in elements
if i["$type"] == 'com.linkedin.voyager.dash.jobs.JobPosting'
]
# break the loop if we're done searching or no results returned
if not new_data:
break
# NOTE: we could also check for the `total` returned in the response.
# This is in data["data"]["paging"]["total"]
results.extend(new_data)
if (
(-1 < limit <= len(results)) # if our results exceed set limit
or len(results) / count >= Linkedin._MAX_REPEATED_REQUESTS
) or len(elements) == 0:
break
self.logger.debug(f"results grew to {len(results)}")
return results
def get_profile_contact_info(self, public_id=None, urn_id=None):
"""Fetch contact information for a given LinkedIn profile. Pass a [public_id] or a [urn_id].
:param public_id: LinkedIn public ID for a profile
:type public_id: str, optional
:param urn_id: LinkedIn URN ID for a profile
:type urn_id: str, optional
:return: Contact data
:rtype: dict
"""
res = self._fetch(
f"/identity/profiles/{public_id or urn_id}/profileContactInfo"
)
data = res.json()
contact_info = {
"email_address": data.get("emailAddress"),
"websites": [],
"twitter": data.get("twitterHandles"),
"birthdate": data.get("birthDateOn"),
"ims": data.get("ims"),
"phone_numbers": data.get("phoneNumbers", []),
}
websites = data.get("websites", [])
for item in websites:
if "com.linkedin.voyager.identity.profile.StandardWebsite" in item["type"]:
item["label"] = item["type"][
"com.linkedin.voyager.identity.profile.StandardWebsite"
]["category"]
elif "" in item["type"]:
item["label"] = item["type"][
"com.linkedin.voyager.identity.profile.CustomWebsite"
]["label"]
del item["type"]
contact_info["websites"] = websites
return contact_info
def get_profile_skills(self, public_id=None, urn_id=None):
"""Fetch the skills listed on a given LinkedIn profile.
:param public_id: LinkedIn public ID for a profile
:type public_id: str, optional
:param urn_id: LinkedIn URN ID for a profile
:type urn_id: str, optional
:return: List of skill objects
:rtype: list
"""
params = {"count": 100, "start": 0}
res = self._fetch(
f"/identity/profiles/{public_id or urn_id}/skills", params=params
)
data = res.json()
skills = data.get("elements", [])
for item in skills:
del item["entityUrn"]
return skills
def get_profile(self, public_id=None, urn_id=None):
"""Fetch data for a given LinkedIn profile.
:param public_id: LinkedIn public ID for a profile
:type public_id: str, optional
:param urn_id: LinkedIn URN ID for a profile
:type urn_id: str, optional
:return: Profile data
:rtype: dict
"""
# NOTE this still works for now, but will probably eventually have to be converted to
# https://www.linkedin.com/voyager/api/identity/profiles/ACoAAAKT9JQBsH7LwKaE9Myay9WcX8OVGuDq9Uw
res = self._fetch(f"/identity/profiles/{public_id or urn_id}/profileView")
data = res.json()
if data and "status" in data and data["status"] != 200:
self.logger.info("request failed: {}".format(data["message"]))
return {}
# massage [profile] data
profile = data["profile"]
if "miniProfile" in profile:
if "picture" in profile["miniProfile"]:
profile["displayPictureUrl"] = profile["miniProfile"]["picture"][
"com.linkedin.common.VectorImage"
]["rootUrl"]
images_data = profile["miniProfile"]["picture"][
"com.linkedin.common.VectorImage"
]["artifacts"]
for img in images_data:
w, h, url_segment = itemgetter(
"width", "height", "fileIdentifyingUrlPathSegment"
)(img)
profile[f"img_{w}_{h}"] = url_segment
profile["profile_id"] = get_id_from_urn(profile["miniProfile"]["entityUrn"])
profile["profile_urn"] = profile["miniProfile"]["entityUrn"]
profile["member_urn"] = profile["miniProfile"]["objectUrn"]
profile["public_id"] = profile["miniProfile"]["publicIdentifier"]
del profile["miniProfile"]
del profile["defaultLocale"]
del profile["supportedLocales"]
del profile["versionTag"]
del profile["showEducationOnProfileTopCard"]
# massage [experience] data
experience = data["positionView"]["elements"]
for item in experience:
if "company" in item and "miniCompany" in item["company"]:
if "logo" in item["company"]["miniCompany"]:
logo = item["company"]["miniCompany"]["logo"].get(
"com.linkedin.common.VectorImage"
)
if logo:
item["companyLogoUrl"] = logo["rootUrl"]
del item["company"]["miniCompany"]
profile["experience"] = experience
# massage [education] data
education = data["educationView"]["elements"]
for item in education:
if "school" in item:
if "logo" in item["school"]:
item["school"]["logoUrl"] = item["school"]["logo"][
"com.linkedin.common.VectorImage"
]["rootUrl"]
del item["school"]["logo"]
profile["education"] = education
# massage [languages] data
languages = data["languageView"]["elements"]
for item in languages:
del item["entityUrn"]
profile["languages"] = languages
# massage [publications] data
publications = data["publicationView"]["elements"]
for item in publications:
del item["entityUrn"]
for author in item.get("authors", []):
del author["entityUrn"]
profile["publications"] = publications
# massage [certifications] data
certifications = data["certificationView"]["elements"]
for item in certifications:
del item["entityUrn"]
profile["certifications"] = certifications
# massage [volunteer] data
volunteer = data["volunteerExperienceView"]["elements"]
for item in volunteer:
del item["entityUrn"]
profile["volunteer"] = volunteer
# massage [honors] data
honors = data["honorView"]["elements"]
for item in honors:
del item["entityUrn"]
profile["honors"] = honors
# massage [projects] data
projects = data["projectView"]["elements"]
for item in projects:
del item["entityUrn"]
profile["projects"] = projects
return profile
def get_profile_connections(self, urn_id):
"""Fetch first-degree connections for a given LinkedIn profile.
:param urn_id: LinkedIn URN ID for a profile
:type urn_id: str
:return: List of search results
:rtype: list
"""
return self.search_people(connection_of=urn_id, network_depth="F")
def get_company_updates(
self, public_id=None, urn_id=None, max_results=None, results=None
):
"""Fetch company updates (news activity) for a given LinkedIn company.
:param public_id: LinkedIn public ID for a company
:type public_id: str, optional
:param urn_id: LinkedIn URN ID for a company
:type urn_id: str, optional
:return: List of company update objects
:rtype: list
"""
if results is None:
results = []
params = {
"companyUniversalName": {public_id or urn_id},
"q": "companyFeedByUniversalName",
"moduleKey": "member-share",
"count": Linkedin._MAX_UPDATE_COUNT,
"start": len(results),
}
res = self._fetch(f"/feed/updates", params=params)
data = res.json()
if (
len(data["elements"]) == 0
or (max_results is not None and len(results) >= max_results)
or (
max_results is not None
and len(results) / max_results >= Linkedin._MAX_REPEATED_REQUESTS
)
):
return results
results.extend(data["elements"])
self.logger.debug(f"results grew: {len(results)}")
return self.get_company_updates(
public_id=public_id,
urn_id=urn_id,
results=results,
max_results=max_results,
)
def get_profile_updates(
self, public_id=None, urn_id=None, max_results=None, results=None
):
"""Fetch profile updates (newsfeed activity) for a given LinkedIn profile.
:param public_id: LinkedIn public ID for a profile
:type public_id: str, optional
:param urn_id: LinkedIn URN ID for a profile
:type urn_id: str, optional
:return: List of profile update objects
:rtype: list
"""
if results is None:
results = []
params = {
"profileId": {public_id or urn_id},
"q": "memberShareFeed",
"moduleKey": "member-share",
"count": Linkedin._MAX_UPDATE_COUNT,
"start": len(results),
}
res = self._fetch(f"/feed/updates", params=params)
data = res.json()
if (
len(data["elements"]) == 0
or (max_results is not None and len(results) >= max_results)
or (
max_results is not None
and len(results) / max_results >= Linkedin._MAX_REPEATED_REQUESTS
)
):
return results
results.extend(data["elements"])
self.logger.debug(f"results grew: {len(results)}")
return self.get_profile_updates(
public_id=public_id,
urn_id=urn_id,
results=results,
max_results=max_results,
)
def get_current_profile_views(self):
"""Get profile view statistics, including chart data.
:return: Profile view data
:rtype: dict
"""
res = self._fetch(f"/identity/wvmpCards")
data = res.json()
return data["elements"][0]["value"][
"com.linkedin.voyager.identity.me.wvmpOverview.WvmpViewersCard"
]["insightCards"][0]["value"][
"com.linkedin.voyager.identity.me.wvmpOverview.WvmpSummaryInsightCard"
][
"numViews"
]
def get_school(self, public_id):
"""Fetch data about a given LinkedIn school.
:param public_id: LinkedIn public ID for a school
:type public_id: str
:return: School data
:rtype: dict
"""
params = {
"decorationId": "com.linkedin.voyager.deco.organization.web.WebFullCompanyMain-12",
"q": "universalName",
"universalName": public_id,
}
res = self._fetch(f"/organization/companies?{urlencode(params)}")
data = res.json()
if data and "status" in data and data["status"] != 200:
self.logger.info("request failed: {}".format(data))
return {}
school = data["elements"][0]
return school
def get_company(self, public_id):
"""Fetch data about a given LinkedIn company.
:param public_id: LinkedIn public ID for a company
:type public_id: str
:return: Company data
:rtype: dict
"""
params = {
"decorationId": "com.linkedin.voyager.deco.organization.web.WebFullCompanyMain-12",
"q": "universalName",
"universalName": public_id,
}
res = self._fetch(f"/organization/companies", params=params)
data = res.json()
if data and "status" in data and data["status"] != 200:
self.logger.info("request failed: {}".format(data["message"]))
return {}
company = data["elements"][0]
return company
def get_conversation_details(self, profile_urn_id):
"""Fetch conversation (message thread) details for a given LinkedIn profile.
:param profile_urn_id: LinkedIn URN ID for a profile
:type profile_urn_id: str
:return: Conversation data
:rtype: dict
"""
# passing `params` doesn't work properly, think it's to do with List().
# Might be a bug in `requests`?
res = self._fetch(
f"/messaging/conversations?\
keyVersion=LEGACY_INBOX&q=participants&recipients=List({profile_urn_id})"
)
data = res.json()
if data["elements"] == []:
return {}
item = data["elements"][0]
item["id"] = get_id_from_urn(item["entityUrn"])
return item