예제 #1
0
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
예제 #2
0
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)
예제 #3
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)
예제 #4
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")
예제 #5
0
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)
예제 #7
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
예제 #8
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))
#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"])
예제 #10
0
from linkedin_api import Linkedin
import argparse, json

parser = argparse.ArgumentParser(description='blah')
parser.add_argument('keyw', metavar='N', type=str,
                    help='keywords for linkedin search')
parser.add_argument('usn', type=str,
                    help='user')
parser.add_argument('pwd', type=str,
                    help='pwd')


args = parser.parse_args()
keyw=args.keyw
api = Linkedin(args.usn, args.pwd, refresh_cookies=True)

search = api.search_people(keywords=keyw)

print(search)

with open("searchResult.json", "w") as fh:
    json.dump(search,fh)
예제 #11
0
                        refresh_cookies=True,
                        debug=True)
file1 = open('./data/search_result/meetup_data.txt', 'r')
Lines = file1.readlines()
for line in Lines:
    firstName = None
    lastname = None
    line = line.replace('\n', "")
    if len(line.split(" ")) >= 2:
        firstName = line.split(" ")[0]
        lastname = line.split(" ")[1]
    else:
        firstName = line.split(" ")[0]
    linked_in_results = None
    linked_in_results = linkedin_api.search_people(regions='us:49',
                                                   firstname=firstName,
                                                   lastname=lastname,
                                                   limit=5)
    print(firstName + ":" + str(len(linked_in_results)))
    for linked_in_result in linked_in_results:
        search_results = None
        search_results = pd.DataFrame()
        profile = linkedin_api.get_profile(urn_id=linked_in_result['urn_id'])
        contact_info = linkedin_api.get_profile_contact_info(
            public_id=linked_in_result['public_id'])
        data_firstname = profile['firstName']
        data_lastname = profile['lastName']
        data_url = "https://www.linkedin.com/in/%s" % \
                   linked_in_result['public_id']
        data_location = profile[
            'locationName'] if "locationName" in profile else " "
        data_country = profile[
예제 #12
0
def postJsonHandler():
    content = request.get_json()
    api = Linkedin(content['email'], content['password'])
    tag = content['tag'].lower()
    keyword = content['keyword'].lower()
    connections = api.search_people(network_depth='F', limit=10)
    querry = []
    for item in connections:

        if (len(querry) >= 5):
            break
        data = {}
        value = item['public_id']
        retrieve = api.get_profile(value)
        if (tag == 'location'):
            if ('locationName' in retrieve):
                if (keyword in retrieve['locationName'].lower()):

                    name = retrieve['firstName'] + ' ' + retrieve['lastName']
                    link = 'https://www.linkedin.com/in/' + item[
                        'public_id'] + '/'
                    #imgr=retrieve['profilePictureOriginalImage']['com.linkedin.common.VectorImage']['rootUrl']
                    #imgi=retrieve['profilePictureOriginalImage']['com.linkedin.common.VectorImage']['artifacts'][1]['fileIdentifyingUrlPathSegment']
                    data['name'] = name
                    data['link'] = link
                    data['initials'] = ''.join(letter[0].upper()
                                               for letter in name.split())
                    data['info'] = retrieve['summary']
                    #data['img']=imgr+imgi
                    querry.append(data)
        elif (tag == 'company'):
            if ('experience' in retrieve):
                if (keyword
                        in retrieve['experience'][0]['companyName'].lower()):
                    name = retrieve['firstName'] + ' ' + retrieve['lastName']
                    link = 'https://www.linkedin.com/in/' + item[
                        'public_id'] + '/'
                    #imgr=retrieve['profilePictureOriginalImage']['com.linkedin.common.VectorImage']['rootUrl']
                    #imgi=retrieve['profilePictureOriginalImage']['com.linkedin.common.VectorImage']['artifacts'][1]['fileIdentifyingUrlPathSegment']
                    data['name'] = name
                    data['link'] = link
                    data['initials'] = ''.join(letter[0].upper()
                                               for letter in name.split())
                    data['info'] = retrieve['summary']
                    #data['img']=imgr+imgi
                    querry.append(data)
        elif (tag == 'title'):
            if ('experience' in retrieve):
                if (keyword in retrieve['experience'][0]['title'].lower()):
                    name = retrieve['firstName'] + ' ' + retrieve['lastName']
                    link = 'https://www.linkedin.com/in/' + item[
                        'public_id'] + '/'
                    #imgr=retrieve['profilePictureOriginalImage']['com.linkedin.common.VectorImage']['rootUrl']
                    #imgi=retrieve['profilePictureOriginalImage']['com.linkedin.common.VectorImage']['artifacts'][1]['fileIdentifyingUrlPathSegment']
                    data['name'] = name
                    data['link'] = link
                    data['initials'] = ''.join(letter[0].upper()
                                               for letter in name.split())
                    data['info'] = retrieve['summary']
                    #data['img']=imgr+imgi
                    querry.append(data)
        elif (tag == 'skills'):
            if ('Skills' in retrieve):
                skillist = retrieve['Skills']
                if any(keyword in s.lower() for s in skillist[1:]):
                    name = retrieve['firstName'] + ' ' + retrieve['lastName']
                    link = 'https://www.linkedin.com/in/' + item[
                        'public_id'] + '/'
                    #imgr=retrieve['profilePictureOriginalImage']['com.linkedin.common.VectorImage']['rootUrl']
                    #imgi=retrieve['profilePictureOriginalImage']['com.linkedin.common.VectorImage']['artifacts'][1]['fileIdentifyingUrlPathSegment']
                    data['name'] = name
                    data['link'] = link
                    data['initials'] = ''.join(letter[0].upper()
                                               for letter in name.split())
                    data['info'] = retrieve['summary']
                    #data['img']=imgr+imgi
                    querry.append(data)

        else:
            name = retrieve['firstName'] + ' ' + retrieve['lastName']

            link = 'https://www.linkedin.com/in/' + item['public_id'] + '/'
            #imgr=retrieve['profilePictureOriginalImage']['com.linkedin.common.VectorImage']['rootUrl']
            #imgi=retrieve['profilePictureOriginalImage']['com.linkedin.common.VectorImage']['artifacts'][1]['fileIdentifyingUrlPathSegment']
            data['name'] = name
            data['link'] = link
            data['initials'] = ''.join(letter[0].upper()
                                       for letter in name.split())
            if ('summary' in retrieve):
                data['info'] = retrieve['summary']
            #data['img']=imgr+imgi
            querry.append(data)

    return jsonify(querry)
예제 #13
0
class Auto_Connector:
    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 _create_config(self):
        """Creates search config file"""
        print('no config detected')

        self.config.add_section('SEARCH')
        self.config.set(
            'SEARCH',
            '# see: https://github.com/ACC1100/linkedin-auto_connect#Config for explanation of values and how to customise'
        )
        self.config.set('SEARCH', 'keywords', '')
        self.config.set('SEARCH', 'keyword_title', '')
        self.config.set('SEARCH', 'network_depths', 'S')
        self.config.set('SEARCH', 'regions', '101452733')
        self.config.set('SEARCH', 'schools', '')

        self.config.add_section('CONNECTIONS')
        self.config.set('CONNECTIONS', 'random', 'False')

        self.config.set('CONNECTIONS', 'message', '')

        self.config.set('CONNECTIONS', 'lower_wait_time', '5')
        self.config.set('CONNECTIONS', 'upper_wait_time', '50')

        with open('config.ini', 'w') as f:
            self.config.write(f)

        print('successfully created new config')

    def _create_credentials(self):
        """Creates login credentials file in PLAIN TEXT"""
        print('no credentials detected')
        username = input("enter username/email: ")
        password = input("enter password: "******"credentials.json", "w") as f:
            f.seek(0)
            json.dump(new_credentials, f, ensure_ascii=False, indent=4)

        print('successfully created new credentials')
        return new_credentials

    def search(self):
        """Searches for people based on config parameters, writes results to JSON and returns results"""
        print("running search")
        results = self.linkedin.search_people(
            keywords=self.config["SEARCH"]['keywords'],
            network_depths=self._string_to_list(
                self.config["SEARCH"]['network_depths']),
            regions=self._string_to_list(self.config["SEARCH"]['regions']),
            schools=self._string_to_list(self.config["SEARCH"]['schools']),
            profile_languages=["en"],
            keyword_title=self.config["SEARCH"]['keyword_title'])
        print("finished search")

        with open("search_results.json", "w") as f:
            f.seek(0)
            json.dump(results, f, ensure_ascii=True, indent=4)
        print("wrote search results to file")

        return results

    def _string_to_list(self, string):
        """converts items separated by comma in string to list form, returns None if string is empty"""
        output = list(map(lambda x: x.strip(), string.split(',')))
        if len(output) == 0:
            return None
        else:
            return output

    def connect(self):
        try:
            with open("search_results.json", "r") as f:
                search_results = json.load(f)

            print(
                "existing search results found, continue with existing results? or create new results?"
            )
            print("0: continue, 1: create new")
            response = input()

            if response == "0":
                search_results = search_results
            elif response == "1":
                search_results = self.search()
            else:
                print("invalid response, closing")
                return

        except FileNotFoundError:
            search_results = self.search()

        print("initiating auto-connect, ctrl+c to cancel at anytime")

        fail_count = 0
        self.search_results = search_results

        signal.signal(
            signal.SIGINT, signal.default_int_handler
        )  # fixes when sometime KeyboardInterrupt doesnt fire? https://stackoverflow.com/questions/40775054/capturing-sigint-using-keyboardinterrupt-exception-works-in-terminal-not-in-scr/40785230#40785230
        try:
            while True:
                if self.config["CONNECTIONS"]['random'] == "True":
                    item = random.choice(self.search_results)
                else:
                    item = self.search_results[0]
                self.search_results.remove(item)  # probably slow

                urn = item['urn_id']
                pid = item['public_id']
                if urn is not None:
                    status = self.linkedin.add_connection(
                        pid,
                        profile_urn=urn,
                        message=self.config["CONNECTIONS"]['message'])
                    if status is True:
                        print(f"Error connecting with: {pid}")
                        fail_count += 1
                    else:
                        print(f"Success: {pid}")
                        fail_count = 0

                    wait = round(
                        random.randrange(
                            int(self.config["CONNECTIONS"]['lower_wait_time']),
                            int(self.config["CONNECTIONS"]
                                ['upper_wait_time'])), 2)
                    print(f"waiting {wait} seconds")
                    time.sleep(wait)

                if fail_count >= 5:
                    print(
                        "ERROR: FAILED 5 CONSECUTIVE CONNECTIONS \n you are likely to be rate limited, double check by manually sending a connection through LinkedIn website"
                    )
                    raise KeyboardInterrupt

        except KeyboardInterrupt:
            with open("search_results.json", "w") as f:
                f.seek(0)
                json.dump(self.search_results, f, ensure_ascii=True, indent=4)
            print('successfully saved updated search before exiting')
            sys.exit(0)