如何使用Google API和REQUESTS缩短网址?

时间:2017-04-14 01:20:11

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

我正在尝试使用Google API缩短网址,但只使用unsigned模块。

代码如下所示:

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

但是longUrl参数在那里!

我做错了什么?

3 个答案:

答案 0 :(得分: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 Quickstart

您可以使用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)

完成上述修改后,请执行示例脚本。您可以获得简短的网址。

答案 1 :(得分:0)

我确信一个人不能仅使用google api请求缩短网址。

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

它有效,但它使用谷歌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身份验证需要用户(在本例中为Me)按下按钮(以确认我可以使用我的信息) )。

答案 2 :(得分:0)

由于问题不是很明确,这个答案分为4个部分。

使用以下方法缩短网址:

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)