【问题标题】:How to Short an URL using Google API and REQUESTS?如何使用 Google API 和 REQUESTS 缩短 URL?
【发布时间】:2017-04-15 15:53:05
【问题描述】:

我正在尝试使用 Google API 缩短 URL,但仅使用 requests 模块。

代码如下所示:

import requests

Key = "" # found in https://developers.google.com/url-shortener/v1/getting_started#APIKey

api = "https://www.googleapis.com/urlshortener/v1/url"

target = "http://www.google.com/"

def goo_shorten_url(url=target):
  payload = {'longUrl': url, "key":Key}
  r = requests.post(api, params=payload)

print(r.text)

当我运行 goo_shorten_url 时,它会返回:

 "error": {
  "errors": [
   {
    "domain": "global",
    "reason": "required",
    "message": "Required",
    "locationType": "parameter",
    "location": "resource.longUrl"
   }

  ],
  "code": 400,
  "message": "Required"
 }

但是longUrl参数是有的!

我做错了什么?

【问题讨论】:

    标签: python-2.7 google-api python-requests google-url-shortener


    【解决方案1】:

    首先,请确认Google API Console已启用“urlshortener api v1”。

    Content-Type 需要作为标头。请使用data 作为请求参数。修改后的样例如下。

    修改后的示例:

    import json
    import requests
    
    Key = "" # found in https://developers.google.com/url-shortener/v1/getting_started#APIKey
    
    api = "https://www.googleapis.com/urlshortener/v1/url"
    
    target = "http://www.google.com/"
    
    def goo_shorten_url(url=target):
      headers = {"Content-Type": "application/json"}
      payload = {'longUrl': url, "key":Key}
      r = requests.post(api, headers=headers, data=json.dumps(payload))
    
    print(r.text)
    

    如果上述脚本不起作用,请使用访问令牌。范围是https://www.googleapis.com/auth/urlshortener。在使用访问令牌的情况下,示例脚本如下。

    示例脚本:

    import json
    import requests
    
    headers = {
        "Authorization": "Bearer " + "access token",
        "Content-Type": "application/json"
    }
    payload = {"longUrl": "http://www.google.com/"}
    r = requests.post(
        "https://www.googleapis.com/urlshortener/v1/url",
        headers=headers,
        data=json.dumps(payload)
    )
    print(r.text)
    

    结果:

    {
     "kind": "urlshortener#url",
     "id": "https://goo.gl/#####",
     "longUrl": "http://www.google.com/"
    }
    

    添加了 1 个:

    在使用tinyurl.com的情况下

    import requests
    
    URL = "http://www.google.com/"
    r = requests.get("http://tinyurl.com/" + "api-create.php?url=" + URL)
    print(r.text)
    

    添加了 2 个:

    如何使用 Python 快速入门

    您可以使用Python Quickstart。如果您没有“google-api-python-client”,请安装它。安装后,请复制粘贴“步骤 3:设置示例”中的示例脚本,并将其创建为 python 脚本。修改点如下两部分。

    1。范围

    之前:

    SCOPES = 'https://www.googleapis.com/auth/drive.metadata.readonly'
    

    之后:

    SCOPES = 'https://www.googleapis.com/auth/urlshortener'
    

    2。脚本

    之前:

    def main():
        """Shows basic usage of the Google Drive API.
    
        Creates a Google Drive API service object and outputs the names and IDs
        for up to 10 files.
        """
        credentials = get_credentials()
        http = credentials.authorize(httplib2.Http())
        service = discovery.build('drive', 'v3', http=http)
    
        results = service.files().list(
            pageSize=10,fields="nextPageToken, files(id, name)").execute()
        items = results.get('files', [])
        if not items:
            print('No files found.')
        else:
            print('Files:')
            for item in items:
                print('{0} ({1})'.format(item['name'], item['id']))
    

    之后:

    def main():
        credentials = get_credentials()
        http = credentials.authorize(httplib2.Http())
        service = discovery.build('urlshortener', 'v1', http=http)
        resp = service.url().insert(body={'longUrl': 'http://www.google.com/'}).execute()
        print(resp)
    

    完成以上修改后,请执行示例脚本。你可以得到短网址。

    【讨论】:

    • 从哪里获得访问令牌?是api键吗? json 版本也无法正常工作。我刚刚发布了问题的简单版本
    • 我很抱歉我的回答很糟糕。我之前已经发布了如何获取访问令牌。请检查一下。那是用的python。 stackoverflow.com/questions/42815450/…
    • 感谢您的链接。我将尝试从中举一个可行的例子。知道如何使用服务帐户而不是 OAuth 吗?
    • 为了使用 API,大多数情况下需要 API 密钥和 OAuth。例如,如果您使用 Google 的快速入门 (developers.google.com/drive/v3/web/quickstart/python) for python,我认为 OAuth 过程会很简单。如果您将使用它,我可以准备一个示例脚本。请告诉我。
    • @zeh 现在我找到了这个。使用tinyurl.com,似乎可以轻松缩短 URL。我试过这个。它工作正常。我在答案上方进行了编辑。请检查一下。
    【解决方案2】:

    我确信不能只使用请求来使用 google api 来缩短网址。

    下面我写了我最终得到的解决方案,

    它可以工作,但它使用 google api,这没问题,但我找不到太多关于它的文档或示例(没有我想要的那么多)。

    要运行代码,记得先安装 google api for python pip install google-api-python-client,然后:

    import json
    
    from oauth2client.service_account import ServiceAccountCredentials
    from apiclient.discovery import build
    
    scopes = ['https://www.googleapis.com/auth/urlshortener']
    
    path_to_json = "PATH_TO_JSON" 
    #Get the JSON file from Google Api [Website]
    (https://console.developers.google.com/apis/credentials), then:
    # 1. Click on Create Credentials. 
    # 2. Select "SERVICE ACCOUNT KEY". 
    # 3. Create or select a Service Account and 
    # 4. save the JSON file.   
    
    credentials = ServiceAccountCredentials.from_json_keyfile_name(path_to_json, scopes)
    
    short = build("urlshortener", "v1",credentials=credentials)
    
    request = short.url().insert(body={"longUrl":"www.google.com"})
    print(request.execute())
    

    我改编自 Google's Manual Page

    之所以如此复杂(至少比我最初的预期要复杂)是为了避免 OAuth2 身份验证需要用户(在本例中为我)按下按钮(以确认我可以使用我的信息)。

    【讨论】:

      【解决方案3】:

      由于问题不是很清楚,因此此答案分为 4 个部分。

      使用以下方法缩短 URL:

      1。 API 密钥。

      2。访问令牌

      3。服务帐号

      4。使用 TinyUrl 的更简单的解决方案。


      API 密钥

      首先,请确认Google API Console已启用“urlshortener api v1”。

      Content-Type 需要作为标头。请使用data 作为请求参数。修改后的样例如下。

      (尽管 API 手册说了什么,但似乎无法正常工作)。

      修改后的示例:

      import json
      import requests
      
      Key = "" # found in https://developers.google.com/url-shortener/v1/getting_started#APIKey
      
      api = "https://www.googleapis.com/urlshortener/v1/url"
      
      target = "http://www.google.com/"
      
      def goo_shorten_url(url=target):
        headers = {"Content-Type": "application/json"}
        payload = {'longUrl': url, "key":Key}
        r = requests.post(api, headers=headers, data=json.dumps(payload))
      
      print(r.text)
      

      访问令牌:

      如果上述脚本不起作用,请使用访问令牌。范围是https://www.googleapis.com/auth/urlshortener。在使用访问令牌的情况下,示例脚本如下。

      Stackoverflow 中的这个答案显示了如何获取访问令牌:Link

      示例脚本:

      import json
      import requests
      
      headers = {
          "Authorization": "Bearer " + "access token",
          "Content-Type": "application/json"
      }
      payload = {"longUrl": "http://www.google.com/"}
      r = requests.post(
          "https://www.googleapis.com/urlshortener/v1/url",
          headers=headers,
          data=json.dumps(payload)
      )
      print(r.text)
      

      结果:

      {
       "kind": "urlshortener#url",
       "id": "https://goo.gl/#####",
       "longUrl": "http://www.google.com/"
      }
      

      使用服务帐号

      为避免用户需要接受 OAuth 身份验证(带有弹出屏幕等),有一个解决方案使用服务帐户在机器之间使用身份验证(如另一个建议的答案中所述)。

      要运行这部分代码,记得先用pip install google-api-python-client安装google api for python,然后:

      import json
      
      from oauth2client.service_account import ServiceAccountCredentials
      from apiclient.discovery import build
      
      scopes = ['https://www.googleapis.com/auth/urlshortener']
      
      path_to_json = "PATH_TO_JSON" 
      #Get the JSON file from Google Api [Website]
      (https://console.developers.google.com/apis/credentials), then:
      # 1. Click on Create Credentials. 
      # 2. Select "SERVICE ACCOUNT KEY". 
      # 3. Create or select a Service Account and 
      # 4. save the JSON file.   
      
      credentials = ServiceAccountCredentials.from_json_keyfile_name(path_to_json, scopes)
      
      short = build("urlshortener", "v1",credentials=credentials)
      
      request = short.url().insert(body={"longUrl":"www.google.com"})
      print(request.execute())
      

      改编自Google's Manual Page

      更简单:

      在使用tinyurl.com的情况下

      import requests
      
      URL = "http://www.google.com/"
      r = requests.get("http://tinyurl.com/" + "api-create.php?url=" + URL)
      print(r.text)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-01-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多