def authenticate(self, refresh_cookies): try: self.application = Linkedin(self.username, self.password, debug=True, refresh_cookies=refresh_cookies) self.authenticated = True return True except Exception as error: logging.exception(error) if 'BAD_EMAIL' in error.args: sg.popup('Incorrect email: try again.', title='Incorrect email', keep_on_top=True) elif 'CHALLENGE' in error.args: sg.popup('Error: LinkedIn requires a sign-in challenge.', title='Linkedin error', keep_on_top=True) elif 'Expecting value: line 1 column 1 (char 0)' in error.args: sg.popup( 'Linkedin is refusing to sign in. Please try again later.', title='Unable to sign in', keep_on_top=True) else: sg.popup( f'Error arguments: {error.args}\n{traceback.format_exc()}', title='Unhandled exception', keep_on_top=True) return False
def getName(account, link): api = Linkedin(account, 'Europa007') theURL = link.replace("\n", "") id = theURL.split("/")[4] profile = api.get_profile(id) lastname = profile['lastName'] firstname = profile['firstName'] name = "{} {}".format(firstname, lastname) return name
class LinkedinEngine: def __init__(self): self.api = Linkedin(LINKEDIN_USER_NAME, LINKEDIN_PASSWORD) def search_company(self, company_name): return self.api.search_people(keywords=company_name) def get_profile(self, user_name): time.sleep(random.randint(0, 3)) user_name = url_parse(user_name) get_contact_dict = self.api.get_profile_contact_info(user_name) get_profile_dict = self.api.get_profile(user_name) return toolz.merge(get_contact_dict, get_profile_dict)
def postJsonHandler(): content = request.get_json() api = Linkedin(content['email'],content['password']) connections=api.search_people(network_depth ='F',limit=5) querry=[] for item in connections: data = {} value = item['urn_id'] retrieve=api.get_profile(value) name=retrieve['firstName']+' '+retrieve['lastName'] link='https://www.linkedin.com/in/'+item['public_id']+'/' data['name'] = name data['link']=link querry.append(data) return jsonify(querry)
def test_search_people_by_keywords_filter(linkedin: Linkedin): results = linkedin.search_people( keyword_first_name="John", keyword_last_name="Smith", include_private_profiles=True, ) assert results
def __init__(self) -> None: self.config = configparser.ConfigParser(allow_no_value=True) self.config.read('config.ini') if len(self.config.sections()) == 0: self._create_config() self.config.read('config.ini') try: with open("credentials.json", "r") as f: self.credentials = json.load(f) except FileNotFoundError: self.credentials = self._create_credentials() print('authenticating') self.linkedin = Linkedin(self.credentials["username"], self.credentials["password"]) print('successfully authenticated')
def query_updates(): app.logger.info('running query updates') api = Linkedin('*****@*****.**', 'prueba1020') location_name = 'Estados Unidos' location_id = 'us:0' terms = Term.query.all() for term in terms: _total = api.searchTotal({ 'keywords': term.term, 'location': location_name, 'locationId': location_id, 'type': 'JOBS', 'query': 'search', }) job = Job(location=location_id, total=_total, term=term) app.logger.info(f'updated {term.term} : {_total}') db.session.add(job) db.session.commit() app.logger.info("finished querying")
def connect_linkedin(): # Authenticate using any Linkedin account credentials try: linkedin_conn[0] = Linkedin(entry_usr.get(), entry_pwd.get()) messagebox.showinfo("Success", "Successfully logged into LinkedIn.", icon="info") except Exception as e: messagebox.showinfo("Error", "Login failed!\nCheck username and password.\n2FA must be disabled in LinkedIn settings.", icon="error") return
def do(self): # pass obj = User.objects.all() try: api = Linkedin('*****@*****.**', 'marvm123') # api = '' except: print("Unable to handle linkedin api check for network connections...") api = '' for i in obj: if i.linkedin_url: username = i.username profile_link = i.linkedin_url profile_link = profile_link.replace('https://www.linkedin.com/in/','').replace('/','') try: profile = api.get_profile(profile_link) getProfile(username,profile) time.sleep(2) except: profile = ""
def linkedin_login(request): # Form response render and linkedin logging in. form = CredsForm(request.POST) if form.is_valid(): username = form.cleaned_data['username'] password = form.cleaned_data['password'] global api # Using Global object for accessing this object in other functions api = Linkedin(username, password) # Logging in using the clients credentials global api_id api_id = id(api) # Creating session return redirect('/index')
def linkedin(self): url = self.data['sites']['linkedin.com']['url'] nickname = self.data['sites']['linkedin.com']['nickname'] login = os.environ.get('LINKEDIN_LOGIN') password = os.environ.get('LINKEDIN_PASSWORD') api = Linkedin(login, password) result = {} profile = api.get_profile(nickname) result.update(profile) contact = api.get_profile_contact_info(nickname) result.update(contact) network = api.get_profile_network_info(nickname) result.update(network) skills = api.get_profile_skills(nickname) result.update({'skills': skills}) result.update({'url': url}) return result
def main(): global email global password print(email) print(password) options = get_options() keyword = options.keyword emailformat = options.emailformat seperator = options.seperator print("[+] emailformat : ", emailformat) print("[+] seperator : ", seperator) print("[+] keyword : ", keyword) print("[+] output example : firstname" + seperator + "lastname@" + emailformat) # Authenticate using any Linkedin account credentials api = Linkedin(email, password) people = api.search_people(keyword_company=keyword) print(people) exit() results = [] for person in people: #print(person['public_id']) try: user = api.get_profile(person['public_id']) except Exception as e: print(e) try: email = user['firstName'] + "." + user[ 'lastName'] + "@" + emailformat + "\n" results.append(email.lower()) print(user['firstName'] + "." + user['lastName']) except Exception as e: print(e) with open("mails_output.txt", "w+") as output: for i in results: output.write(i) output.write("\n")
def login(username, password, cache, cleanup): try: api = Linkedin(username, password, refresh_cookies=not cleanup) except ChallengeException: print('CHALLENGE') return except UnauthorizedException: print('UNAUTHORIZED') return for cookie in api.client.session.cookies: builder = f'{cookie.name}={cookie.value}' for key in ['expires', 'path', 'domain']: if cookie.__dict__[key]: builder += f'; {key}={cookie.__dict__[key]}' if cookie.__dict__['_rest']['SameSite']: sameSite = cookie.__dict__['_rest']['SameSite'] builder += f'; samesite={sameSite.lower()}' builder += ('; secure' if cookie.__dict__['secure'] else '') print(builder) if cleanup: try: os.remove(_get_cookies_filepath(username)) except OSError: pass
def __main__(): try: global api global profiles global names global workbook global worksheet global left8Format global boldleft8Format global boldmid9Format api = Linkedin('YOUR_LOGIN_CRED_MAIL', 'YOUR_LOGIN_CRED_PASS') profiles = [] names = [] LINK.getUserNames() LINK.getProfiles() for profile in profiles: print( "=============================================================================" ) print( "=============================================================================" ) print(" | USER: "******"firstName"] + " " + profile["lastName"]) name = profile["firstName"] + " " + profile["lastName"] headLine = profile.get("headline", "??") workbook = xlsxwriter.Workbook(name + ".xlsx") worksheet = workbook.add_worksheet() worksheet.set_column('A:A', 33) worksheet.set_column('B:B', 18) worksheet.set_column('C:C', 43) worksheet.set_column('D:D', 30) left8Format = workbook.add_format({ 'bold': False, 'align': 'left', 'text_wrap': True, 'valign': 'vcenter', 'font_name': 'Verdana', 'font_size': '8' }) boldleft8Format = workbook.add_format({ 'bold': True, 'align': 'left', 'text_wrap': True, 'valign': 'vcenter', 'font_name': 'Verdana', 'font_size': '8' }) boldmid9Format = workbook.add_format({ 'bold': True, 'align': 'mid', 'valign': 'vcenter', 'text_wrap': True, 'top': 5, 'bottom': 5, 'left': 5, 'right': 5, 'border_color': '#cedcc0', 'bg_color': '#cedcc0', 'font_color': '#5b727d', 'font_name': 'Verdana', 'font_size': '9' }) worksheet.write('A1', 'Prospect', boldmid9Format) worksheet.write('B1', 'Career Summary', boldmid9Format) worksheet.write('C1', ' ', boldmid9Format) worksheet.write('D1', 'Education', boldmid9Format) worksheet.write('A2', name, boldleft8Format) worksheet.write('A3', headLine, left8Format) worksheet.write('A4', 'Date of Birth:', boldleft8Format) worksheet.write('A5', ' ', left8Format) worksheet.write('A6', 'Language:', boldleft8Format) worksheet.write('A6', ' ', left8Format) LINK.getEdu(profile) LINK.getExp(profile) workbook.close() print( "=============================================================================" ) except Exception as err: if "Failed to establish a new connection" in str(err): print( "\n\tFailed to establish a new connection... Check availability\n" ) else: print(err)
def __init__(self): self.api = Linkedin(LINKEDIN_USER_NAME, LINKEDIN_PASSWORD)
from linkedin_api import Linkedin from random import randint from re import split linkedin = Linkedin("*****@*****.**", "twiggyboy3") companies = [] results = linkedin.stub_people_search("Senior Network Architect", count=49, start=randint(0, 100))["data"]["elements"] for element in results: try: for snippet in element["hitInfo"]["snippets"]: company = split(' at ', snippet["heading"]["text"]) companies.append(company[len(company)-1]) except KeyError: continue try: companies.remove("present") except ValueError: pass print(list(set(companies)))
def test_search_people_by_keywords_filter(linkedin: Linkedin): results = linkedin.search_people(keyword_first_name="John", keyword_last_name="Smith") assert results assert results[0]["public_id"]
class LinkedinSearch: """ The class to search for subjects and put them into `found` and `potential` categories. """ def __init__(self, user_input): self.first_name = user_input["first_name"] self.last_name = user_input["last_name"] self.keyword_company = user_input["company"] self.keyword_school = user_input["school"] self.keyword_title = user_input["job_title"] self._api = None self._found_subjects = [] self._potential_subjects = [] def linkedin_search(self): """ Call other methods to search for subjects and put them into appropriate categories. """ self.__linkedin_authenticate() self.__linkedin_search_for_subjects() def __linkedin_authenticate(self): """Authenticate using LinkedIn login and password.""" self._api = LinkedinAPI(os.getenv("LINKEDIN_LOGIN"), os.getenv("LINKEDIN_PASSWORD")) def __linkedin_search_for_subjects(self): """ Search for a subject in an ideal case or, if not found, find potential candidates. """ self.__linkedin_search_in_ideal_case() if not self._found_subjects: self.__linkedin_search_for_potential_candidate() def __linkedin_search_in_ideal_case(self): """ Search for a subject in an ideal case if provided all necessary information. """ if self.keyword_company and self.keyword_school and self.keyword_title: self._found_subjects = self._api.search_people( keyword_first_name=self.first_name, keyword_last_name=self.last_name, keyword_company=self.keyword_company, keyword_school=self.keyword_school, keyword_title=self.keyword_title, ) def __linkedin_search_for_potential_candidate(self): """ Search for potential candidates with any provided information. """ for i in range(3): try: results = self._api.search_people( keyword_first_name=self.first_name, keyword_last_name=self.last_name, keyword_company=None if i != 0 else self.keyword_company if self.keyword_company else 1 / 0, keyword_school=None if i != 1 else self.keyword_school if self.keyword_school else 1 / 0, keyword_title=None if i != 2 else self.keyword_title if self.keyword_title else 1 / 0, ) except ZeroDivisionError: continue self._potential_subjects.extend(results)
import sys import json from traitlets import link import os from linkedin_api import Linkedin import pandas as pd import time linkedin_api = Linkedin("*****@*****.**","password", refresh_cookies=True, debug=True) comapany = linkedin_api.get_company(public_id="google") comapanyid = int(comapany['url'].split('/')[len(comapany['url'].split('/')) - 1]) results = linkedin_api.search_people1(start=0,limit=10,current_company=comapanyid,regions="us:49",keywords="Software Engineer") print(len(results)) search_results = pd.DataFrame() for result in results: contact_info = linkedin_api.get_profile_contact_info(public_id=result['public_id']) profile = linkedin_api.get_profile(urn_id=result['urn_id']) data_firstname = profile['firstName'] data_lastname = profile['lastName'] data_url = "https://www.linkedin.com/in/%s" % \ result['public_id'] data_location = profile['locationName'] if "locationName" in profile else " " data_country = profile['geoCountryName'] if "geoCountryName" in profile else " " data_jobpost = profile['headline'] if "headline" in profile else " " data_exp = "" for exp in profile['experience']: data_exp += "[" data_exp += exp['locationName'] + "|" if "locationName" in exp else " " data_exp += exp['companyName'] + "|" if "companyName" in exp else " " data_exp += str(exp['timePeriod']['startDate']['month']) + " " if "timePeriod" in exp and "startDate" in exp['timePeriod'] and "month" in exp['timePeriod']['startDate'] else " " data_exp += str(exp['timePeriod']['startDate']['year']) + "|" if "timePeriod" in exp and "startDate" in exp['timePeriod'] and "year" in exp['timePeriod']['startDate'] else " "
for i in range(1, 16): with open('143_data/%s.csv' % i, newline='') as csvfile: rows = csv.reader(csvfile) for row in rows: if row[1] == 'Title_link': continue title.add(row[1]) csvfile.close() p_list = [] for t in title: p_list.append(t.split('/')[-2]) # Authenticate using any Linkedin account credentials api = Linkedin('*****@*****.**', 'Hello!11') pro_list = [] n = 1 for p in p_list: profile = api.get_profile(p) pro_list.append(profile) print(n, ' ', p) n += 1 p_list = [] with open('profile_list_remains.txt', 'r') as f: lines = f.readlines() for line in lines:
def linkedinextract(id): url11 = request.args.get('url11') anna = request.args.get('aname') anem = request.args.get('aemail') anad = request.args.get('aaddress') anph = request.args.get('aphone') anni = request.args.get('anic') skills1 = request.args.get('dskills') name1 = request.args.get('dname') projects1 = request.args.get('dproject') degree1 = request.args.get('ddeg') univercity1 = request.args.get('duni') experience11 = request.args.get('dexp') phone1 = request.args.get('dmobile') address1 = request.args.get('daddress') nic1 = request.args.get('daddress') print(url11) lname = [] lskills = [] lexperience = [] ldegree = [] luniversity = [] lemail1 = [] lmobile = [] # try: url11 = 'ravindu-landekumbura-19950214' linkedin1 = Linkedin('*****@*****.**', 'net@telecom') linkprofile = linkedin1.get_profile(url11) print(linkprofile) contact = linkedin1.get_profile_contact_info(url11) print(contact) lname = [] lname1o = linkprofile['firstName'] lname.append(json.dumps(lname1o)) # lname="Ravindu landekumbura" lskills = [] skills = (linkprofile['skills']) for skill in skills: z = skill['name'] ls = json.dumps(z) lskills.append(ls) lexperience = [] experience1 = (linkprofile['experience']) for ex in experience1: z = ex['companyName'], ex['title'] d = json.dumps(z) lexperience.append(d) university1 = (linkprofile['education']) print(university1) luniversity = [] ldegree = [] for sch in university1: school = sch['school'] print(school) nm = school['schoolName'] luniversity.append(nm) dm = sch['degreeName'] ldegree.append(dm) lluniversity = json.dumps(luniversity) lldegree = json.dumps(ldegree) lexperience1 = json.dumps(experience1) llskills = json.dumps(lskills) lemail1 = json.dumps(contact['email_address']) lmobile = json.dumps(contact['phone_numbers']) # except: print('cannot connect') mycursor.execute("SELECT email from user where id=%s;", [id]) rows = mycursor.fetchall() for ele in rows: email1 = json.dumps(ele[0]).replace('[]', "") if request.method == 'POST': uid = id uemail = request.form['uemail'] upassword = request.form['upassword'] sql2 = "INSERT INTO cv_reg (id,email,password) VALUES (%s, %s, %s)" val = (uid, uemail, upassword) mycursor.execute(sql2, val) mydb.commit() return redirect( url_for('clogin', id1=uid, nameu=uemail, passu=upassword)) return render_template('linkedin.html', urlx=url11, skillsx=skills1, namex=name1, emailx=email1, projectsx=projects1, degreesx=degree1, universityx=univercity1, experiencex=experience11, mobilex=phone1, addressx=address1, linkedinx=url11, nicx=nic1, namexx=lname, skillsxx=llskills, experiencexx=lexperience, unversityxx=lluniversity, degreexx=lldegree, emailxx=lemail1, mobilexx=lmobile, aname=anna, aemail=anem, aaddress=anad, aphone=anph, anic=anni, ski=lskills, len=len(lskills))
# # LinkedIn Authentication # In[2]: from linkedin_api import Linkedin # In[3]: email = '*****@*****.**' password = '******' # In[4]: # Authenticate using any Linkedin account credentials api = Linkedin(email, password) # In[5]: username = '******' # In[6]: # Get a profile profile = api.get_profile(username) # # Extract Experience # In[7]: for a in profile['experience']:
from linkedin_api import Linkedin import json # Authenticate using any Linkedin account credentials api = Linkedin('*****@*****.**', 'Prince@123') # GET all connected profiles (1st, 2nd and 3rd degree) of a given profile connections = api.search_people(connection_of='vishala-maddineni-62392656', network_depth='F', limit=100) first_degree = [] for item in connections: # if (item['distance'] == 'DISTANCE_1'): # Increment the existing user's count. first_degree.append(item) querry = [] for item in first_degree: data = {} value = item['urn_id'] retrieve = api.get_profile(value) name = retrieve['firstName'] + ' ' + retrieve['lastName'] experience = retrieve['experience'] skills = retrieve['skills'] link = 'https://www.linkedin.com/in/' + item['public_id'] + '/' data['name'] = name data['link'] = link
def getConnections(req: func.HttpRequest) -> func.HttpResponse: results=[] content = req.get_json() logging.info(content) tag = content['tag'].lower() keyword = content['keyword'].lower() email = content['email'] filteredConnections = [] if (path.exists(email+'.txt') == False): api = Linkedin(content['email'], content['password']) logging.info("Starting Search People") connections = api.search_people() for connection in connections: id = connection['public_id'] if (id not in filteredConnections and connection['distance'] == 'DISTANCE_1' and len(filteredConnections) <= 5): filteredConnections.append(id) for public_id in filteredConnections: retrieve = api.get_profile(public_id) name = retrieve['firstName']+' '+retrieve['lastName'] link = 'https://www.linkedin.com/in/'+public_id+'/' # imgr=retrieve['profilePictureOriginalImage']['com.linkedin.common.VectorImage']['rootUrl'] # imgi=retrieve['profilePictureOriginalImage']['com.linkedin.common.VectorImage']['artifacts'][1]['fileIdentifyingUrlPathSegment'] # data['img']=imgr+imgi data = {} data['name'] = name data['link'] = link data['initials'] = ''.join(letter[0].upper() for letter in name.split()) if ('skills' in retrieve): data['skills'] = retrieve['skills'] data['headline'] = retrieve['headline'] if ('experience' in retrieve and len(retrieve['experience']) > 0): data['company'] = retrieve['experience'][0]['companyName'] data['title'] = retrieve['experience'][0]['title'] if ('locationName' in retrieve): data['location'] = retrieve['locationName'] elif ('geoLocationName' in retrieve): data['location'] = retrieve['geoLocationName'] profilesInfo['people'].append(data) with open(email+'.txt', 'w') as file: file.write(json.dumps(profilesInfo)) with open(email+'.txt', 'r') as file: profiles = json.load(file) for profile in profiles['people']: if (len(results) >= 5): break if (tag == 'location' and 'location' in profile and keyword.lower() in profile['location'].lower()): data = populateData(profile) results.append(data) elif (tag == 'company' and 'company' in profile and keyword.lower() in profile['company'].lower()): data = populateData(profile) results.append(data) elif (tag == 'title' and 'title' in profile and keyword.lower() in profile['title'].lower()): data = populateData(profile) results.append(data) elif (tag == 'skills' and 'skills' in profile): skillist = profile['skills'] if any(keyword.lower() in s['name'].lower() for s in skillist[1:]): data = populateData(profile) results.append(data) return func.HttpResponse(json.dumps(results))
import json from linkedin_api import Linkedin with open('credentials.json', 'r') as f: credentials = json.load(f) if credentials: linkedin = Linkedin(credentials['username'], credentials['password']) profile = linkedin.get_profile('ACoAABQ11fIBQLGQbB1V1XPBZJsRwfK5r1U2Rzw') profile['contact_info'] = \ linkedin.get_profile_contact_info('ACoAABQ11fIBQLGQbB1V1XPBZJsRwfK5r1U2Rzw') connections = linkedin.get_profile_connections(profile['profile_id'])
def get_linkedin_object(): username, password = get_key() # Authenticate using any Linkedin account credentials linkedin_object = Linkedin(username=username, password=password) return linkedin_object
def linkedin(): return Linkedin(TEST_LINKEDIN_USERNAME, TEST_LINKEDIN_PASSWORD, refresh_cookies=True)
#using linkedin-api grabs profile info, takes in public profile id. this is like www.linkedin.com/in/***your_profile_name_11101*** from linkedin_api import Linkedin api = Linkedin('your@email', 'your_pass!') #get profiles from public ids, private ids will be included in results import pandas as pd df = pd.read_csv('linkedin_input.csv') ids = list(df['id']) profile_data = [] from random import randint from time import sleep for i in ids: profile_info = api.get_profile(i) print('getting', i) profile_data.append(profile_info) sleep(randint(2, 6)) #keys returned: ['summary', 'industryName', 'lastName', 'locationName', #'student', 'elt', 'industryUrn', 'firstName', 'entityUrn', #'location', 'headline', 'displayPictureUrl', 'profile_id', #'experience', 'skills', 'education'] ids = [] summaries = [] locations = [] headlines = [] current_company = [] industry = []
from linkedin_api import Linkedin # Authenticate using any Linkedin account credentials api = Linkedin('*****@*****.**', 'pipuchis10') # GET a profile profile = api.searchTotal({ 'keywords': 'java', 'location': 'Estados Unidos', 'locationId': 'us:0', 'type': 'JOBS', 'query': 'search', })
def __linkedin_authenticate(self): """Authenticate using LinkedIn login and password.""" self._api = LinkedinAPI(os.getenv("LINKEDIN_LOGIN"), os.getenv("LINKEDIN_PASSWORD"))