示例#1
0
    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
示例#2
0
    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
示例#3
0
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
    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
示例#5
0
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')
示例#6
0
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 __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')
示例#8
0
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")
示例#9
0
 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 = ""  
示例#10
0
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")
示例#11
0
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
示例#12
0
def main(skip_existing: bool = False, force: bool = False):
    """
    Pull company metadata from LinkedIn and write to tags in README.md.

    Add tags <!--linkedin:company_name--><!--endlinkedin--> to README.md, where
    `company_name` corresponds to the last piece of the company's LinkedIn URL.
    """

    # Read LinkedIn account details from .env or terminal.
    load_dotenv()
    email = os.getenv("LINKEDIN_EMAIL")
    password = os.getenv("LINKEDIN_PASSWORD")
    if email is None or password is None:
        typer.echo(
            "Enter LinkedIn account to query the API (or use .env file)")
        typer.echo(
            "WARNING: Accounts with excessive API calls are sometimes blocked "
            "by LinkedIn.")
        email = input("LinkedIn email: ")
        password = getpass.getpass()
    else:
        typer.echo("LinkedIn account details read from .env")

    # Set up LinkedIn API.
    api = Linkedin(email, password, refresh_cookies=True)

    def create_company_description(name):
        """Create a markup description of the company from its LinkedIn `name`."""
        company = api.get_company(name)

        # Number of staff members.
        staff = company["staffCount"]
        staff_url = f"https://www.linkedin.com/company/{name}/people/"
        md = f" &nbsp;[👷 {staff}]({staff_url})"

        # Number of job openings.
        # Search for all jobs by the (full) company name first.
        # For generic company names, this will return a lot of false positives.
        full_name = company["name"]
        jobs_list = api.search_jobs(full_name, location_name="Berlin, Germany")
        # Then, filter by the company URN (unique identifier from LinkedIn).
        urn = company["entityUrn"]
        filtered_jobs_list = [
            job for job in jobs_list
            if job["companyDetails"].get("company", "") == urn
        ]
        jobs = len(filtered_jobs_list)
        if jobs > 0:
            jobs_url = f"https://www.linkedin.com/company/{name}/jobs/"
            md += f" &nbsp;[🔎 {jobs}]({jobs_url})"

        # Funding round.
        if "fundingData" in company:
            funding_type = company["fundingData"]["lastFundingRound"][
                "fundingType"]
            # Only show "Seed" or "Series X", otherwise show "X rounds" (there are some
            # other weird funding type names).
            if funding_type in [
                    "SEED", "SERIES_A", "SERIES_B", "SERIES_C", "SERIES_D"
            ]:
                funding = funding_type.replace("_", " ").title()
            else:
                funding_rounds = company["fundingData"]["numFundingRounds"]
                funding = f"{funding_rounds} round"
                if funding_rounds > 1:
                    funding += "s"
            funding_url = company["fundingData"][
                "fundingRoundListCrunchbaseUrl"]
            md += f" &nbsp;[💰 {funding}]({funding_url})"

        return md

    # Read README.md.
    with open("README.md", "r") as f:
        text = f.read()

    # Replace old descriptions with new ones.
    typer.echo("-" * 80)
    for name, old_desc in re.findall(
            "<!--linkedin:(.*?)-->(.*?)<!--endlinkedin-->", text):
        if skip_existing and old_desc:
            typer.echo(name + ": skipped")
        else:
            typer.echo(name + ":")
            new_desc = create_company_description(name)
            typer.echo(new_desc)
            text = text.replace(
                f"<!--linkedin:{name}-->{old_desc}<!--endlinkedin-->",
                f"<!--linkedin:{name}-->{new_desc}<!--endlinkedin-->",
            )
            typer.echo()

    # typer.echo updated file content.
    typer.echo("-" * 80)
    typer.echo()
    typer.echo(text)
    typer.echo()
    typer.echo("-" * 80)

    # Write to file.
    if force:
        write = "y"
    else:
        write = input("Review modified text above. Write to README.md? (Y/n) ")
    if write.lower() in ["", "y", "yes"]:
        os.rename("README.md", "old-README.md")
        with open("README.md", "w") as f:
            f.write(text)
        typer.secho("✓ Updated README.md (old file stored in old-README.md",
                    fg="green")
    else:
        typer.secho("✗ Did NOT update README.md", fg="red")
示例#13
0
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)))
#https://github.com/tomquirk/linkedin-api/blob/master/DOCS.md
#https://github.com/tomquirk/linkedin-api/blob/master/linkedin_api/linkedin.py
#https://github.com/tomquirk/linkedin-api/
from linkedin_api import Linkedin
api = Linkedin('login email', 'Password123$$')

search = api.search_people(
    keywords='company name,sales manager,account executive', industries=['43'])

array = []
for i in range(len(search)):
    try:
        if search[i]['distance'] == "DISTANCE_3":
            pass
        else:
            print(search[i]['public_id'])
            array.append((search[i]['public_id']))
    except:
        pass

array2 = []
for i in array[:10]:
    data = api.get_profile(i)
    array2.append(data)

for i in array2:
    print(i["firstName"], i["lastName"],
          i["experience"][0]["companyName"])  #i["headline"])
示例#15
0
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 get_linkedin_object():
    username, password = get_key()
    # Authenticate using any Linkedin account credentials
    linkedin_object = Linkedin(username=username, password=password)
    return linkedin_object
示例#17
0
 def __init__(self):
     self.api = Linkedin(LINKEDIN_USER_NAME, LINKEDIN_PASSWORD)
示例#18
0
    labels=labels,
    values=values,
)

trace1 = go.Pie(**common_props, textinfo='percent', textposition='outside')

trace2 = go.Pie(**common_props, textinfo='label', textposition='inside')

iplot([trace1, trace2], filename='basic_pie_chart')

# # LinkedIn

# In[9]:

from linkedin_api import Linkedin
api = Linkedin("*****@*****.**", "psosm1234")

# In[2]:

username = "******"

# # Extract Education

# In[3]:

profile = api.get_profile(username)  # returns a dictionary
edu = profile["education"]  # returns list of dictionaries

# In[4]:

# extracting education for analysing event timeline
示例#19
0
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'])
# # 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']:
示例#21
0
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))
示例#22
0
from flask import Flask, jsonify,request,render_template,make_response
from flask import *
import json 
from linkedin_api import Linkedin

app = Flask(__name__)
app.secret_key = "spc"

### Credentials ##############################################################################################################
api = Linkedin('*****@*****.**', 'hr123456')
##############################################################################################################################


##############################################################################################################################





def scrapSingleUser(uri):
    try:
        profile = api.get_profile(uri)
    #summary name location headline experience skills
        user_data = []
        user_data.append(uri)
        if 'firstName' in profile:
            if 'lastName' in profile:
                user_data.append(profile['firstName']+" "+profile['lastName'])
            else:
                user_data.append(profile['firstName'])
        elif 'lastName' in profile:
示例#23
0
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:
示例#24
0
import urllib
import requests
import json
from linkedin_api import Linkedin

if __name__ == '__main__':

    api = Linkedin('*****@*****.**', 'DelhiBelly11#Snatch00')
    profile = api.get_profile('venkata-ratnadeep-suri')
    contact_info = api.get_profile_contact_info('venkata-ratnadeep-suri')
    connections = api.get_profile_connections('venkata-ratnadeep-suri')

    with open('venkata-ratnadeep-suri.txt', 'w') as p:
        json.dump(profile, p)

    with open('venkata-ratnadeep-suri', 'w') as c:
        json.dump(contact_info, c)

    with open('venkata-ratnadeep-suri', 'w') as connect:
        json.dump(connections, connect)
#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 = []
示例#26
0
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 " "
def linkedin():
    return Linkedin(TEST_LINKEDIN_USERNAME,
                    TEST_LINKEDIN_PASSWORD,
                    refresh_cookies=True)
示例#28
0
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))
示例#29
0
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',
})
示例#30
0
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