6. Functions deep diveΒΆ

from config import *
def requestFacetDict(text, kind, cookies=cookies, headers=headers, accountId=accountId):
    query = "https://www.linkedin.com/campaign-manager-api/campaignManagerAdTargetingEntities?query={0}&accountId={1}&facets=List(urn%3Ali%3AadTargetingFacet%3A{2})&q=queryAndMultiFacetTypeahead"""
    query = query.format(text, accountId, kind)

    response = requests.get(query, headers=headers, cookies=cookies)
    parsed = json.loads(response.content)

    try:
        return parsed['elements'][0]
    except:
        return
def encodeFacet(criteria, kind='locations'):
    assert kind in ['locations', 'genders', 'ageRanges', 'degrees', 'fieldsOfStudy', 'seniorities', 'industries']

    if any('urn:urn' in criterion for criterion in criteria if criterion is not None):
        return ','.join(criteria)

    tc = ""

    if not criteria:
        return tc
    elif type(criteria) is list:
        if type(criteria[0]) is str:
            new_criteria = []
            for criterion in criteria:
                location_dict = requestFacetDict(criterion, kind)
                if location_dict is not None:
                    new_criteria.append(location_dict)
                else:
                    print(f"URN for '{criterion}' not found")

            if not new_criteria:
                print("The API did not return any results for these parameters")
                return tc

            criteria = new_criteria

        if type(criteria[0]) is dict:
            try:
                for i, criterion in enumerate(criteria):
                    criterion['name'] = criterion['name'].replace('&', 'and')
                    tc += "(urn:" + encodeInner(criterion['urn'])
                    tc += ",name:" + encodeInner(criterion["name"])
                    tc += ",facetUrn:" + encodeInner(criterion['facetUrn'])
                    tc += ")"
                    if i < len(criteria) - 1:
                        tc += ","
                return tc
            except:
                print("The dictionaries in the list do not have the required keys and/or values.")
                assert False
        elif criteria[0] is None:
            return tc
        else:
            print("The function's argument should be a list of strings or a list of correctly formatted dicts.")
            assert False
    else:
        print("The function's argument should be a list of strings or a list of correctly formatted dicts.")
        assert False
def createRequestDataForAudienceCounts(locations,
                                       genders=None, age_groups=None,
                                       degrees=None, fields=None,
                                       seniorities=None, industries=None):
    if age_groups is None:
        age_groups = []
    if degrees is None:
        degrees = []
    if fields is None:
        fields = []
    if seniorities is None:
        seniorities = []
    if industries is None:
        industries = []

    tc = """
q=targetingCriteria&cmTargetingCriteria=
(include:
 (and:List
  (
   (or:List
    (
     (facet:
      (urn:urn:li:adTargetingFacet:locations,name:Locations
      ),segments:List
      ( """
    tc += encodeFacet(criteria=locations, kind='locations')
    tc += """   
      )
     )
    )
   ),
   (or:List
    (
     (facet:
      (urn:urn:li:adTargetingFacet:genders,name:Member Gender
      ),segments:List
      ( """
    tc += encodeFacet(criteria=genders, kind='genders')
    tc += """  
      )
     )
    )
   ),
   (or:List
    (
     (facet:
      (urn:urn:li:adTargetingFacet:ageRanges,name:Member Age
      ),segments:List
      ( """
    tc += encodeFacet(criteria=age_groups, kind='ageRanges')
    tc += """
      )
     )
    )
   ),
   (or:List
    (
     (facet:
      (urn:urn:li:adTargetingFacet:degrees,name:Degrees
      ),segments:List
      ( """
    tc += encodeFacet(criteria=degrees, kind='degrees')
    tc += """   
      )
     )
    )
   ),
   (or:List
    (
     (facet:
      (urn:urn:li:adTargetingFacet:fieldsOfStudy,name:Fields of Study
      ),segments:List
      ( """
    tc += encodeFacet(criteria=fields, kind='fieldsOfStudy')
    tc += """   
      )
     )
    )
   ),
   (or:List
    (
     (facet:
      (urn:urn:li:adTargetingFacet:seniorities,name:Job Seniorities
      ),segments:List
      ( """
    tc += encodeFacet(criteria=seniorities, kind='seniorities')
    tc += """   
      )
     )
    )
   ),
   (or:List
    (
     (facet:
      (urn:urn:li:adTargetingFacet:industries,name:Company Industries
      ),segments:List
      ( """
    tc += encodeFacet(criteria=industries, kind='industries')
    tc += """   
      )
     )
    )
   )
  )
 ),exclude:
 (or:List
  (
  )
 )
)&withValidation=true

"""
    tc = linkedinEncodeURL(tc)
    tc = tc.replace(' ','')
    return tc