Получить URL-адреса профиля пользователя в социальных сетях, используя график знаний - PullRequest
0 голосов
/ 04 марта 2020

Я пытаюсь получить социальный профиль (твиттер, Facebook ...) людей в поиске Google и сохранить его в итоге в листе Excel с помощью API поиска в графе знаний. Пожалуйста, посмотрите на код, который я использовал ниже и JSON return. Мой вопрос: есть ли способ получить чьи-то ссылки на социальные сети с помощью API поиска в графе знаний? Пожалуйста, помогите.

вот мой код и JSON возврат.

import json
import urllib.parse
import requests
# from requests.packages.urllib3.exceptions import InsecureRequestWarning

# requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
from requests.packages.urllib3.exceptions import InsecureRequestWarning


print('Knowledge Graph API')
api_key = open('api-key.txt').read()
while True:
    query = input('Enter query: ')
    querynum = input('How many results do you want? (Number): ')
    queryDesc = input('Return Knowledge Graph description? (Y/N): ')
    typequestion = input('Add entity filter? (Y/N): ')
    if typequestion == 'Y':
        print('Check Schema.org for list of entity "types": https://schema.org/docs/schemas.html')
        kptype = input('What type of entity do you want? ')

    service_url = 'https://kgsearch.googleapis.com/v1/entities:search'
    params = {
        'query': str(query),
        'limit': int(querynum),
        'indent': True,
        'key': api_key,
}

    if typequestion == 'Y':
        params['types'] = kptype

    url = f'{service_url}?{urllib.parse.urlencode(params)}'
    print(url)
    response = requests.get(url, verify=False)
    json_response = json.loads(response.text)

    print(f'Query: {query}' + '\n')

    try:
        for element in json_response['itemListElement']:
            if queryDesc == 'Y':
                print(element['result']['name'] + ' (ID: ' + element['result']['@id'] + ')' + ' \
                (Score: ' + str(element['resultScore']) + ')' + 'Description: ' + element['result']['description'])
            else:
                print(element['result']['name'] + ' (ID: ' + element['result']['@id'] + ')' + ' \
                (Score: ' + str(element['resultScore']) + ')')
    except KeyError:
        print('<Error: Name not found>')

    print('')
    savefiles = input('Save files locally?(Y/N) ')
    if savefiles == 'Y':
        download_dir = 'knowledge-graph-results.csv'
        file = open(download_dir, 'w')
        columnTitleRow = "Query, Name, MID, Score, Description\n"
        file.write(columnTitleRow)

        try:
            for element in json_response['itemListElement']:
                if queryDesc == 'Y':
                    q = query
                    name = element['result']['name']
                    ID = element['result']['@id']
                    score = element['resultScore']
                    description = element['result']['description']
                    descrip2 = f'"{description}"'

                    row = f'{q},{name},{ID},{score},{descrip2}\n'
                    file.write(row)
                else:
                    q = query
                    name = element['result']['name']
                    ID = element['result']['@id']
                    score = element['resultScore']
                    description = element['result']['description']
                    row2 = f'{q},{name},{ID},{score}\n'
                    file.write(row2)
        except KeyError:
            print('')
    if savefiles == 'Y':
        print(f'Success. Results saved locally at {download_dir}.')
        file.close()
    choice = input('Continue Querying?(Y/N): ')
    if choice == 'N':
        break

input()

JSON:

{
  "@context": {
    "kg": "http://g.co/kg",
    "detailedDescription": "goog:detailedDescription",
    "resultScore": "goog:resultScore",
    "goog": "http://schema.googleapis.com/",
    "EntitySearchResult": "goog:EntitySearchResult",
    "@vocab": "http://schema.org/"
  },
  "@type": "ItemList",
  "itemListElement": [
    {
      "resultScore": 16892.138671875,
      "@type": "EntitySearchResult",
      "result": {
        "description": "44th U.S. President",
        "detailedDescription": {
          "license": "https://en.wikipedia.org/wiki/Wikipedia:Text_of_Creative_Commons_Attribution-ShareAlike_3.0_Unported_License",
          "url": "https://en.wikipedia.org/wiki/Barack_Obama",
          "articleBody": "Barack Hussein Obama II is an American attorney and politician who served as the 44th president of the United States from 2009 to 2017. A member of the Democratic Party, he was the first African American to be elected to the presidency. He previously served as a Senator from Illinois from 2005 to 2008.\nObama was born in 1961 in Honolulu, Hawaii, two years after the territory was admitted to the Union as the 50th state. After graduating from Columbia University in 1983, he worked as a community organizer in Chicago. In 1988, he enrolled in Harvard Law School, where he was the first black president of the Harvard Law Review. "
        },
        "url": "https://www.barackobama.com/",
        "@id": "kg:/m/02mjmr",
        "image": {
          "url": "https://commons.wikimedia.org/wiki/File:Official_portrait_of_Barack_Obama-2.jpg",
          "contentUrl": "https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcQVKLSn9tDb1fSHRSRxqS-Y_tOdb10JvSOzE0lDZBV3RXGXScjD"
        },
        "name": "Barack Obama",
        "@type": [
          "Thing",
          "Person"
        ]
      }
    },
    {
      "resultScore": 2347.44091796875,
      "@type": "EntitySearchResult",
      "result": {
        "@type": [
          "Thing"
        ],
        "description": "Family",
        "detailedDescription": {
          "url": "https://en.wikipedia.org/wiki/Family_of_Barack_Obama",
          "articleBody": "The family of Barack Obama, the 44th president of the United States, and his wife Michelle Obama is made up of people of Kenyan, African-American, and Old Stock American ancestry. ",
          "license": "https://en.wikipedia.org/wiki/Wikipedia:Text_of_Creative_Commons_Attribution-ShareAlike_3.0_Unported_License"
        },
        "@id": "kg:/m/06_wyyq",
        "image": {
          "contentUrl": "https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcRg4Cm43JQwyESg8IANemN4c7hA3ZJQvbiSvmFRY5PozVUVbVpx",
          "url": "https://en.wikipedia.org/wiki/File:Barack_Obama_family_portrait_2011.jpg"
        },
        "name": "Family of Barack Obama"
      }
    },
    {
      "resultScore": 1415.568359375,
      "@type": "EntitySearchResult",
      "result": {
        "@type": [
          "Thing",
          "Person"
        ],
        "description": "Kenyan economist",
        "detailedDescription": {
          "license": "https://en.wikipedia.org/wiki/Wikipedia:Text_of_Creative_Commons_Attribution-ShareAlike_3.0_Unported_License",
          "url": "https://en.wikipedia.org/wiki/Barack_Obama_Sr.",
          "articleBody": "Barack Hussein Obama Sr. was a Kenyan senior governmental economist and the father of Barack Obama, the 44th president of the United States. He is a central figure of his son's memoir, Dreams from My Father. Obama married in 1954 and had two children with his first wife, Kezia. "
        },
        "@id": "kg:/m/03qccxj",
        "image": {
          "contentUrl": "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQfsSm-kZfrazpdFMtTymmY1UbUwbQS2VU6hsuG_2BcpDF780M7",
          "url": "https://commons.wikimedia.org/wiki/File:Sarah_Onyango_home-Barack_Obama_Sr_grave-2.jpg"
        },
        "name": "Barack Obama Sr."
      }
    },
    {
      "result": {
        "detailedDescription": {
          "url": "https://en.wikipedia.org/wiki/President_Barack_Obama_(painting)",
          "articleBody": "President Barack Obama is a 2018 portrait of Barack Obama by the artist Kehinde Wiley for the National Portrait Gallery.",
          "license": "https://en.wikipedia.org/wiki/Wikipedia:Text_of_Creative_Commons_Attribution-ShareAlike_3.0_Unported_License"
        },
        "@id": "kg:/g/11f6153_20",
        "@type": [
          "Thing",
          "VisualArtwork"
        ],
        "name": "President Barack Obama",
        "description": "Painting by Kehinde Wiley"
      },
      "resultScore": 233.42329406738281,
      "@type": "EntitySearchResult"
    },
    {
      "resultScore": 206.8387145996094,
      "@type": "EntitySearchResult",
      "result": {
        "name": "Barack Obama: Son of Promise, Child of Hope",
        "description": "Book by Nikki Grimes",
        "@id": "kg:/m/04x6ghg",
        "@type": [
          "Book",
          "Thing"
        ]
      }
    },
    {
      "resultScore": 131.70478820800781,
      "@type": "EntitySearchResult",
      "result": {
        "@type": [
          "Thing"
        ],
        "name": "Barack Obama in comics",
        "description": "Comic book character",
        "detailedDescription": {
          "url": "https://en.wikipedia.org/wiki/Barack_Obama_in_comics",
          "articleBody": "Barack Obama has appeared as a character in comic books published by a number of publishing companies, sometimes appearing as a realistic fictionalized version of himself and sometimes as a spoof.",
          "license": "https://en.wikipedia.org/wiki/Wikipedia:Text_of_Creative_Commons_Attribution-ShareAlike_3.0_Unported_License"
        },
        "@id": "kg:/m/05f34xs"
      }
    },
    {
      "@type": "EntitySearchResult",
      "result": {
        "name": "Barack Obama",
        "description": "Fictional character",
        "@id": "kg:/m/09ryzqt",
        "@type": [
          "Thing"
        ]
      },
      "resultScore": 52.269332885742188
    },
    {
      "@type": "EntitySearchResult",
      "result": {
        "@id": "kg:/m/0h2yj33",
        "@type": [
          "Thing"
        ],
        "name": "Barack Obama"
      },
      "resultScore": 24
    },
    {
      "result": {
        "name": "Barack Obama",
        "@id": "kg:/g/11b80c5gfl",
        "@type": [
          "Thing"
        ]
      },
      "resultScore": 24,
      "@type": "EntitySearchResult"
    }
  ]
}
...