linkedin-api 1.0.1__tar.gz → 2.0.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2018 Tom Quirk
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,236 @@
1
+ Metadata-Version: 2.1
2
+ Name: linkedin_api
3
+ Version: 2.0.0
4
+ Summary: Python wrapper for the Linkedin API
5
+ Home-page: https://github.com/tomquirk/linkedin-api
6
+ Author: Tom Quirk
7
+ Author-email: tomquirkacc@gmail.com
8
+ License: MIT
9
+ Platform: UNKNOWN
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: License :: OSI Approved :: MIT License
12
+ Classifier: Operating System :: OS Independent
13
+ Description-Content-Type: text/markdown
14
+ License-File: LICENSE
15
+
16
+ # Linkedin API for Python
17
+
18
+ <h3 align="center">Sponsors</h3>
19
+
20
+ <p align="center">
21
+ <a href="https://lix-it.com/pages/linkedin-api?utm_campaign=influencer%20marketing&utm_source=github&utm_medium=social&utm_content=tomquirk" target="_blank">
22
+ <img height="45px" style="margin-right:15px" src="./assets/logos/lix.png" alt="Lix">
23
+ </a>
24
+ <a href="https://nubela.co/proxycurl/?utm_campaign=influencer%20marketing&utm_source=github&utm_medium=social&utm_term=-&utm_content=tom%20quirk" target="_blank">
25
+ <img height="45px" src="./assets/logos/proxycurl.png" alt="proxycurl">
26
+ </a>
27
+ <a href="https://iscraper.io/" target="_blank">
28
+ <img height="45px" src="./assets/logos/iscraper.png" alt="serpsbot">
29
+ </a>
30
+ <a href="https://www.piloterr.com/?ref=tomquirk" target="_blank">
31
+ <img height="45px" src="./assets/logos/piloterr.png" alt="piloterr">
32
+ </a>
33
+ </p>
34
+
35
+ <h5 align="center"><a href="https://github.com/sponsors/tomquirk/sponsorships?sponsor=tomquirk&tier_id=96653&preview=false" target="_blank">Become a sponsor</a></h5>
36
+
37
+ ---
38
+
39
+ Programmatically send messages, get jobs, and search profiles with a regular Linkedin user account.
40
+
41
+ No "official" API access required - just use a valid Linkedin account!
42
+
43
+ **Caution**: This library is not officially supported by LinkedIn. Using it might violate LinkedIn's Terms of Service. Use it at your own risk.
44
+
45
+ ## Installation
46
+
47
+ > Python >= 3.6 required
48
+
49
+ To install the linkedin_api package, use the following command:
50
+
51
+ ```bash
52
+ pip3 install git+https://github.com/tomquirk/linkedin-api.git
53
+ ```
54
+
55
+ ### Quick Start
56
+
57
+ > See all methods on the [documentation website](https://linkedin-api.readthedocs.io/).
58
+
59
+ Below is a basic example of how to use linkedin_api:
60
+
61
+ ```python
62
+ from linkedin_api import Linkedin
63
+
64
+ # Authenticate using any Linkedin account credentials
65
+ api = Linkedin('reedhoffman@linkedin.com', '*******')
66
+
67
+ # GET a profile
68
+ profile = api.get_profile('billy-g')
69
+
70
+ # GET a profiles contact info
71
+ contact_info = api.get_profile_contact_info('billy-g')
72
+
73
+ # GET 1st degree connections of a given profile
74
+ connections = api.get_profile_connections('1234asc12304')
75
+ ```
76
+
77
+ ## Commercial Alternative
78
+
79
+ > This is a sponsored section
80
+
81
+ Scrape public LinkedIn profile data at scale with [Proxycurl APIs](https://nubela.co/proxycurl/?utm_campaign=influencer%20marketing&utm_source=github&utm_medium=social&utm_term=-&utm_content=tom%20quirk).
82
+
83
+ - Scraping Public profiles are battle tested in court in HiQ VS LinkedIn case.
84
+ - GDPR, CCPA, SOC2 compliant
85
+ - High rate limit - 300 requests/minute
86
+ - Fast - APIs respond in ~2s
87
+ - Fresh data - 88% of data is scraped real-time, other 12% are not older than 29 days
88
+ - High accuracy
89
+ - Tons of data points returned per profile
90
+
91
+ Built for developers, by developers.
92
+
93
+ > End sponsored section
94
+
95
+ ## Documentation
96
+
97
+ For comprehensive documentation, including available methods and parameters, visit the [documentation](https://linkedin-api.readthedocs.io/).
98
+
99
+ [Learn more](#how-it-works) about how it works.
100
+
101
+ ## Disclaimer
102
+
103
+ This library is not endorsed or supported by LinkedIn. It is an unofficial library intended for educational purposes and personal use only. By using this library, you agree to not hold the author or contributors responsible for any consequences resulting from its usage.
104
+
105
+ ## Contributing
106
+
107
+ We welcome contributions! [Learn how to find endpoints](#to-find-endpoints)
108
+
109
+ ## Development Setup
110
+
111
+ ### Dependencies
112
+
113
+ - Python 3.7
114
+ - A valid Linkedin user account (don't use your personal account, if possible)
115
+ - `pipenv` (optional)
116
+
117
+ ### Development installation
118
+
119
+ 1. Create a `.env` config file. An example is provided in `.env.example` - you include at least all of the settings set there.
120
+ 2. Using pipenv...
121
+
122
+ ```bash
123
+ pipenv install --dev
124
+ pipenv shell
125
+ ```
126
+
127
+ ### Running tests
128
+
129
+ ```bash
130
+ python -m pytest tests
131
+ ```
132
+
133
+ ### Troubleshooting
134
+
135
+ #### I keep getting a `CHALLENGE`
136
+
137
+ Linkedin will throw you a curve ball in the form of a Challenge URL. We currently don't handle this, and so you're kinda screwed. We think it could be only IP-based (i.e. logging in from different location). Your best chance at resolution is to log out and log back in on your browser.
138
+
139
+ **Known reasons for Challenge** include:
140
+
141
+ - 2FA
142
+ - Rate-limit - "It looks like you’re visiting a very high number of pages on LinkedIn.". Note - n=1 experiment where this page was hit after ~900 contiguous requests in a single session (within the hour) (these included random delays between each request), as well as a bunch of testing, so who knows the actual limit.
143
+
144
+ Please add more as you come across them.
145
+
146
+ #### Search problems
147
+
148
+ - Mileage may vary when searching general keywords like "software" using the standard `search` method. They've recently added some smarts around search whereby they group results by people, company, jobs etc. if the query is general enough. Try to use an entity-specific search method (i.e. search_people) where possible.
149
+
150
+ ## How it works
151
+
152
+ > Before using this project, please consult the [Terms and Conditions](#terms-and-conditions) and [Legal Notice](#legal).
153
+
154
+ This project attempts to provide a simple Python interface for the Linkedin API.
155
+
156
+ > Do you mean the [legit Linkedin API](https://developer.linkedin.com/)?
157
+
158
+ NO! To retrieve structured data, the [Linkedin Website](https://linkedin.com) uses a service they call **Voyager**. Voyager endpoints give us access to pretty much everything we could want from Linkedin: profiles, companies, connections, messages, etc. - anything that you can see on linkedin.com, we can get from Voyager.
159
+
160
+ This project aims to provide complete coverage for Voyager.
161
+
162
+ [How does it work?](#in-depth-overview)
163
+
164
+ ### In-depth overview
165
+
166
+ Voyager endpoints look like this:
167
+
168
+ ```text
169
+ https://www.linkedin.com/voyager/api/identity/profileView/tom-quirk
170
+ ```
171
+
172
+ Or, more clearly
173
+
174
+ ```text
175
+ ___________________________________ _______________________________
176
+ | base path | resource |
177
+ https://www.linkedin.com/voyager/api /identity/profileView/tom-quirk
178
+ ```
179
+
180
+ They are authenticated with a simple cookie, which we send with every request, along with a bunch of headers.
181
+
182
+ To get a cookie, we POST a given username and password (of a valid Linkedin user account) to `https://www.linkedin.com/uas/authenticate`.
183
+
184
+ ### To find endpoints
185
+
186
+ We're looking at the Linkedin website and we spot some data we want. What now?
187
+
188
+ The most reliable method to find the relevant endpoint is to:
189
+
190
+ 1. `view source`
191
+ 2. `command-f`/search the page for some keyword in the data. This will exist inside of a `<code>` tag.
192
+ 3. Scroll down to the **next adjacent element** which will be another `<code>` tag, probably with an `id` that looks something like
193
+
194
+ ```html
195
+ <code style="display: none" id="datalet-bpr-guid-3900675">
196
+ {"request":"/voyager/api/identity/profiles/tom-quirk/profileView","status":200,"body":"bpr-guid-3900675"}
197
+ </code>
198
+ ```
199
+
200
+ 4. The value of `request` is the url! 🤘
201
+
202
+ You can also use the `network` tab in you browsers developer tools, but you will encounter mixed results.
203
+
204
+ ### How Clients query Voyager
205
+
206
+ linkedin.com queries data using the [Rest-li Protocol](https://linkedin.github.io/rest.li/spec/protocol). Rest-li is an internal query language/syntax where clients (like linkedin.com) to specify what data they want (similar to the GraphQL concept).
207
+
208
+ Here's an example of making a request for an organisation's `name` and `groups` (the Linkedin groups it manages):
209
+
210
+ ```text
211
+ /voyager/api/organization/companies?decoration=(name,groups*~(entityUrn,largeLogo,groupName,memberCount,websiteUrl,url))&q=universalName&universalName=linkedin
212
+ ```
213
+
214
+ The "querying" happens in the `decoration` parameter, which looks like
215
+
216
+ ```text
217
+ (
218
+ name,
219
+ groups*~(entityUrn,largeLogo,groupName,memberCount,websiteUrl,url)
220
+ )
221
+ ```
222
+
223
+ So here, we request an organisation name, and a list of groups, where for each group we want `largeLogo`, `groupName`, etc.
224
+
225
+ Different endpoints use different parameters (and perhaps even different syntaxes) to specify these queries. Notice that the above query had a parameter `q` whose value was `universalName`; the query was then specified with the `decoration` parameter.
226
+
227
+ In contrast, the `/search/cluster` endpoint uses `q=guided`, and specifies its query with the `guided` parameter, whose value is something like
228
+
229
+ ```text
230
+ List(v->PEOPLE)
231
+ ```
232
+
233
+ It could be possible to document (and implement a nice interface for) this query language - as we add more endpoints to this project, I'm sure it will become more clear if such a thing would be possible (and if it's worth it).
234
+
235
+
236
+
@@ -0,0 +1,219 @@
1
+ # Linkedin API for Python
2
+
3
+ <h3 align="center">Sponsors</h3>
4
+
5
+ <p align="center">
6
+ <a href="https://lix-it.com/pages/linkedin-api?utm_campaign=influencer%20marketing&utm_source=github&utm_medium=social&utm_content=tomquirk" target="_blank">
7
+ <img height="45px" style="margin-right:15px" src="./assets/logos/lix.png" alt="Lix">
8
+ </a>
9
+ <a href="https://nubela.co/proxycurl/?utm_campaign=influencer%20marketing&utm_source=github&utm_medium=social&utm_term=-&utm_content=tom%20quirk" target="_blank">
10
+ <img height="45px" src="./assets/logos/proxycurl.png" alt="proxycurl">
11
+ </a>
12
+ <a href="https://iscraper.io/" target="_blank">
13
+ <img height="45px" src="./assets/logos/iscraper.png" alt="serpsbot">
14
+ </a>
15
+ <a href="https://www.piloterr.com/?ref=tomquirk" target="_blank">
16
+ <img height="45px" src="./assets/logos/piloterr.png" alt="piloterr">
17
+ </a>
18
+ </p>
19
+
20
+ <h5 align="center"><a href="https://github.com/sponsors/tomquirk/sponsorships?sponsor=tomquirk&tier_id=96653&preview=false" target="_blank">Become a sponsor</a></h5>
21
+
22
+ ---
23
+
24
+ Programmatically send messages, get jobs, and search profiles with a regular Linkedin user account.
25
+
26
+ No "official" API access required - just use a valid Linkedin account!
27
+
28
+ **Caution**: This library is not officially supported by LinkedIn. Using it might violate LinkedIn's Terms of Service. Use it at your own risk.
29
+
30
+ ## Installation
31
+
32
+ > Python >= 3.6 required
33
+
34
+ To install the linkedin_api package, use the following command:
35
+
36
+ ```bash
37
+ pip3 install git+https://github.com/tomquirk/linkedin-api.git
38
+ ```
39
+
40
+ ### Quick Start
41
+
42
+ > See all methods on the [documentation website](https://linkedin-api.readthedocs.io/).
43
+
44
+ Below is a basic example of how to use linkedin_api:
45
+
46
+ ```python
47
+ from linkedin_api import Linkedin
48
+
49
+ # Authenticate using any Linkedin account credentials
50
+ api = Linkedin('reedhoffman@linkedin.com', '*******')
51
+
52
+ # GET a profile
53
+ profile = api.get_profile('billy-g')
54
+
55
+ # GET a profiles contact info
56
+ contact_info = api.get_profile_contact_info('billy-g')
57
+
58
+ # GET 1st degree connections of a given profile
59
+ connections = api.get_profile_connections('1234asc12304')
60
+ ```
61
+
62
+ ## Commercial Alternative
63
+
64
+ > This is a sponsored section
65
+
66
+ Scrape public LinkedIn profile data at scale with [Proxycurl APIs](https://nubela.co/proxycurl/?utm_campaign=influencer%20marketing&utm_source=github&utm_medium=social&utm_term=-&utm_content=tom%20quirk).
67
+
68
+ - Scraping Public profiles are battle tested in court in HiQ VS LinkedIn case.
69
+ - GDPR, CCPA, SOC2 compliant
70
+ - High rate limit - 300 requests/minute
71
+ - Fast - APIs respond in ~2s
72
+ - Fresh data - 88% of data is scraped real-time, other 12% are not older than 29 days
73
+ - High accuracy
74
+ - Tons of data points returned per profile
75
+
76
+ Built for developers, by developers.
77
+
78
+ > End sponsored section
79
+
80
+ ## Documentation
81
+
82
+ For comprehensive documentation, including available methods and parameters, visit the [documentation](https://linkedin-api.readthedocs.io/).
83
+
84
+ [Learn more](#how-it-works) about how it works.
85
+
86
+ ## Disclaimer
87
+
88
+ This library is not endorsed or supported by LinkedIn. It is an unofficial library intended for educational purposes and personal use only. By using this library, you agree to not hold the author or contributors responsible for any consequences resulting from its usage.
89
+
90
+ ## Contributing
91
+
92
+ We welcome contributions! [Learn how to find endpoints](#to-find-endpoints)
93
+
94
+ ## Development Setup
95
+
96
+ ### Dependencies
97
+
98
+ - Python 3.7
99
+ - A valid Linkedin user account (don't use your personal account, if possible)
100
+ - `pipenv` (optional)
101
+
102
+ ### Development installation
103
+
104
+ 1. Create a `.env` config file. An example is provided in `.env.example` - you include at least all of the settings set there.
105
+ 2. Using pipenv...
106
+
107
+ ```bash
108
+ pipenv install --dev
109
+ pipenv shell
110
+ ```
111
+
112
+ ### Running tests
113
+
114
+ ```bash
115
+ python -m pytest tests
116
+ ```
117
+
118
+ ### Troubleshooting
119
+
120
+ #### I keep getting a `CHALLENGE`
121
+
122
+ Linkedin will throw you a curve ball in the form of a Challenge URL. We currently don't handle this, and so you're kinda screwed. We think it could be only IP-based (i.e. logging in from different location). Your best chance at resolution is to log out and log back in on your browser.
123
+
124
+ **Known reasons for Challenge** include:
125
+
126
+ - 2FA
127
+ - Rate-limit - "It looks like you’re visiting a very high number of pages on LinkedIn.". Note - n=1 experiment where this page was hit after ~900 contiguous requests in a single session (within the hour) (these included random delays between each request), as well as a bunch of testing, so who knows the actual limit.
128
+
129
+ Please add more as you come across them.
130
+
131
+ #### Search problems
132
+
133
+ - Mileage may vary when searching general keywords like "software" using the standard `search` method. They've recently added some smarts around search whereby they group results by people, company, jobs etc. if the query is general enough. Try to use an entity-specific search method (i.e. search_people) where possible.
134
+
135
+ ## How it works
136
+
137
+ > Before using this project, please consult the [Terms and Conditions](#terms-and-conditions) and [Legal Notice](#legal).
138
+
139
+ This project attempts to provide a simple Python interface for the Linkedin API.
140
+
141
+ > Do you mean the [legit Linkedin API](https://developer.linkedin.com/)?
142
+
143
+ NO! To retrieve structured data, the [Linkedin Website](https://linkedin.com) uses a service they call **Voyager**. Voyager endpoints give us access to pretty much everything we could want from Linkedin: profiles, companies, connections, messages, etc. - anything that you can see on linkedin.com, we can get from Voyager.
144
+
145
+ This project aims to provide complete coverage for Voyager.
146
+
147
+ [How does it work?](#in-depth-overview)
148
+
149
+ ### In-depth overview
150
+
151
+ Voyager endpoints look like this:
152
+
153
+ ```text
154
+ https://www.linkedin.com/voyager/api/identity/profileView/tom-quirk
155
+ ```
156
+
157
+ Or, more clearly
158
+
159
+ ```text
160
+ ___________________________________ _______________________________
161
+ | base path | resource |
162
+ https://www.linkedin.com/voyager/api /identity/profileView/tom-quirk
163
+ ```
164
+
165
+ They are authenticated with a simple cookie, which we send with every request, along with a bunch of headers.
166
+
167
+ To get a cookie, we POST a given username and password (of a valid Linkedin user account) to `https://www.linkedin.com/uas/authenticate`.
168
+
169
+ ### To find endpoints
170
+
171
+ We're looking at the Linkedin website and we spot some data we want. What now?
172
+
173
+ The most reliable method to find the relevant endpoint is to:
174
+
175
+ 1. `view source`
176
+ 2. `command-f`/search the page for some keyword in the data. This will exist inside of a `<code>` tag.
177
+ 3. Scroll down to the **next adjacent element** which will be another `<code>` tag, probably with an `id` that looks something like
178
+
179
+ ```html
180
+ <code style="display: none" id="datalet-bpr-guid-3900675">
181
+ {"request":"/voyager/api/identity/profiles/tom-quirk/profileView","status":200,"body":"bpr-guid-3900675"}
182
+ </code>
183
+ ```
184
+
185
+ 4. The value of `request` is the url! 🤘
186
+
187
+ You can also use the `network` tab in you browsers developer tools, but you will encounter mixed results.
188
+
189
+ ### How Clients query Voyager
190
+
191
+ linkedin.com queries data using the [Rest-li Protocol](https://linkedin.github.io/rest.li/spec/protocol). Rest-li is an internal query language/syntax where clients (like linkedin.com) to specify what data they want (similar to the GraphQL concept).
192
+
193
+ Here's an example of making a request for an organisation's `name` and `groups` (the Linkedin groups it manages):
194
+
195
+ ```text
196
+ /voyager/api/organization/companies?decoration=(name,groups*~(entityUrn,largeLogo,groupName,memberCount,websiteUrl,url))&q=universalName&universalName=linkedin
197
+ ```
198
+
199
+ The "querying" happens in the `decoration` parameter, which looks like
200
+
201
+ ```text
202
+ (
203
+ name,
204
+ groups*~(entityUrn,largeLogo,groupName,memberCount,websiteUrl,url)
205
+ )
206
+ ```
207
+
208
+ So here, we request an organisation name, and a list of groups, where for each group we want `largeLogo`, `groupName`, etc.
209
+
210
+ Different endpoints use different parameters (and perhaps even different syntaxes) to specify these queries. Notice that the above query had a parameter `q` whose value was `universalName`; the query was then specified with the `decoration` parameter.
211
+
212
+ In contrast, the `/search/cluster` endpoint uses `q=guided`, and specifies its query with the `guided` parameter, whose value is something like
213
+
214
+ ```text
215
+ List(v->PEOPLE)
216
+ ```
217
+
218
+ It could be possible to document (and implement a nice interface for) this query language - as we add more endpoints to this project, I'm sure it will become more clear if such a thing would be possible (and if it's worth it).
219
+
@@ -4,7 +4,7 @@
4
4
  from .linkedin import Linkedin
5
5
 
6
6
  __title__ = "linkedin_api"
7
- __version__ = "1.0.1"
7
+ __version__ = "2.0.0"
8
8
  __description__ = "Python Wrapper for the Linkedin API"
9
9
 
10
10
  __license__ = "MIT"
@@ -1,8 +1,8 @@
1
1
  import requests
2
- import pickle
3
2
  import logging
4
-
5
- import linkedin_api.settings as settings
3
+ from linkedin_api.cookie_repository import CookieRepository
4
+ from bs4 import BeautifulSoup
5
+ import json
6
6
 
7
7
  logger = logging.getLogger(__name__)
8
8
 
@@ -21,13 +21,14 @@ class Client(object):
21
21
  """
22
22
 
23
23
  # Settings for general Linkedin API calls
24
- API_BASE_URL = "https://www.linkedin.com/voyager/api"
24
+ LINKEDIN_BASE_URL = "https://www.linkedin.com"
25
+ API_BASE_URL = f"{LINKEDIN_BASE_URL}/voyager/api"
25
26
  REQUEST_HEADERS = {
26
27
  "user-agent": " ".join(
27
28
  [
28
- "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_5)",
29
+ "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_5)",
29
30
  "AppleWebKit/537.36 (KHTML, like Gecko)",
30
- "Chrome/66.0.3359.181 Safari/537.36",
31
+ "Chrome/83.0.4103.116 Safari/537.36",
31
32
  ]
32
33
  ),
33
34
  # "accept": "application/vnd.linkedin.normalized+json+2.1",
@@ -38,7 +39,6 @@ class Client(object):
38
39
  }
39
40
 
40
41
  # Settings for authenticating with Linkedin
41
- AUTH_BASE_URL = "https://www.linkedin.com"
42
42
  AUTH_REQUEST_HEADERS = {
43
43
  "X-Li-User-Agent": "LIAuthLibrary:3.2.4 \
44
44
  com.linkedin.LinkedIn:8.8.1 \
@@ -49,47 +49,92 @@ class Client(object):
49
49
  "Accept-Language": "en-us",
50
50
  }
51
51
 
52
- def __init__(self, debug=False, refresh_cookies=False):
52
+ def __init__(
53
+ self, *, debug=False, refresh_cookies=False, proxies={}, cookies_dir=None
54
+ ):
53
55
  self.session = requests.session()
54
- self.session.headers = Client.REQUEST_HEADERS
55
-
56
+ self.session.proxies.update(proxies)
57
+ self.session.headers.update(Client.REQUEST_HEADERS)
58
+ self.proxies = proxies
56
59
  self.logger = logger
60
+ self.metadata = {}
57
61
  self._use_cookie_cache = not refresh_cookies
62
+ self._cookie_repository = CookieRepository(cookies_dir=cookies_dir)
63
+
58
64
  logging.basicConfig(level=logging.DEBUG if debug else logging.INFO)
59
65
 
60
66
  def _request_session_cookies(self):
61
67
  """
62
68
  Return a new set of session cookies as given by Linkedin.
63
69
  """
64
- if self._use_cookie_cache:
65
- self.logger.debug("Attempting to use cached cookies")
66
- try:
67
- with open(settings.COOKIE_FILE_PATH, "rb") as f:
68
- cookies = pickle.load(f)
69
- if cookies:
70
- return cookies
71
- except FileNotFoundError:
72
- self.logger.debug("Cookie file not found. Requesting new cookies.")
70
+ self.logger.debug("Requesting new cookies.")
73
71
 
74
72
  res = requests.get(
75
- f"{Client.AUTH_BASE_URL}/uas/authenticate",
73
+ f"{Client.LINKEDIN_BASE_URL}/uas/authenticate",
76
74
  headers=Client.AUTH_REQUEST_HEADERS,
75
+ proxies=self.proxies,
77
76
  )
78
-
79
77
  return res.cookies
80
78
 
81
- def _set_session_cookies(self, cookiejar):
79
+ def _set_session_cookies(self, cookies):
82
80
  """
83
- Set cookies of the current session and save them to a file.
81
+ Set cookies of the current session and save them to a file named as the username.
84
82
  """
85
- self.session.cookies = cookiejar
83
+ self.session.cookies = cookies
86
84
  self.session.headers["csrf-token"] = self.session.cookies["JSESSIONID"].strip(
87
85
  '"'
88
86
  )
89
- with open(settings.COOKIE_FILE_PATH, "wb") as f:
90
- pickle.dump(cookiejar, f)
87
+
88
+ @property
89
+ def cookies(self):
90
+ return self.session.cookies
91
91
 
92
92
  def authenticate(self, username, password):
93
+ if self._use_cookie_cache:
94
+ self.logger.debug("Attempting to use cached cookies")
95
+ cookies = self._cookie_repository.get(username)
96
+ if cookies:
97
+ self.logger.debug("Using cached cookies")
98
+ self._set_session_cookies(cookies)
99
+ self._fetch_metadata()
100
+ return
101
+
102
+ self._do_authentication_request(username, password)
103
+ self._fetch_metadata()
104
+
105
+ def _fetch_metadata(self):
106
+ """
107
+ Get metadata about the "instance" of the LinkedIn application for the signed in user.
108
+
109
+ Store this data in self.metadata
110
+ """
111
+ res = requests.get(
112
+ f"{Client.LINKEDIN_BASE_URL}",
113
+ cookies=self.session.cookies,
114
+ headers=Client.AUTH_REQUEST_HEADERS,
115
+ proxies=self.proxies,
116
+ )
117
+
118
+ soup = BeautifulSoup(res.text, "lxml")
119
+
120
+ clientApplicationInstanceRaw = soup.find(
121
+ "meta", attrs={"name": "applicationInstance"}
122
+ )
123
+ if clientApplicationInstanceRaw:
124
+ clientApplicationInstanceRaw = (
125
+ clientApplicationInstanceRaw.attrs.get("content") or {}
126
+ )
127
+ clientApplicationInstance = json.loads(clientApplicationInstanceRaw)
128
+ self.metadata["clientApplicationInstance"] = clientApplicationInstance
129
+
130
+ clientPageInstanceIdRaw = soup.find(
131
+ "meta", attrs={"name": "clientPageInstanceId"}
132
+ )
133
+ if clientPageInstanceIdRaw:
134
+ clientPageInstanceId = clientPageInstanceIdRaw.attrs.get("content") or {}
135
+ self.metadata["clientPageInstanceId"] = clientPageInstanceId
136
+
137
+ def _do_authentication_request(self, username, password):
93
138
  """
94
139
  Authenticate with Linkedin.
95
140
 
@@ -104,10 +149,11 @@ class Client(object):
104
149
  }
105
150
 
106
151
  res = requests.post(
107
- f"{Client.AUTH_BASE_URL}/uas/authenticate",
152
+ f"{Client.LINKEDIN_BASE_URL}/uas/authenticate",
108
153
  data=payload,
109
154
  cookies=self.session.cookies,
110
155
  headers=Client.AUTH_REQUEST_HEADERS,
156
+ proxies=self.proxies,
111
157
  )
112
158
 
113
159
  data = res.json()
@@ -122,3 +168,4 @@ class Client(object):
122
168
  raise Exception()
123
169
 
124
170
  self._set_session_cookies(res.cookies)
171
+ self._cookie_repository.save(res.cookies, username)