我试图使用Google API来缩短网址,但只使用了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参数就在那里!
我做错了什么?
发布于 2017-04-14 10:03:55
请先确认Google API Console开启了urlshortener接口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)完成上述修改后,请执行示例脚本。您可以获得简短的URL。
发布于 2017-04-15 00:44:39
我确信,一个人不能只使用请求来使用google api来缩短url。
下面我写了我最终得到的解决方案,
它可以工作,但它使用google api,这是可以的,但我找不到很多关于它的文档或示例(不像我想要的那么多)。
要运行代码,请记住首先使用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改编的。
它必须如此复杂(至少比我一开始预期的要复杂)的原因是为了避免需要用户(在本例中是我)按下按钮(以确认我可以使用我的信息)的OAuth2身份验证。
发布于 2017-04-15 15:32:06
由于问题不是很清楚,这个答案分为4个部分。
使用以下方式缩短URL:
1. API密钥。
2.访问令牌
3.服务帐号
4.使用TinyUrl更简单的解决方案。
API密钥
请先确认Google API Console开启了urlshortener接口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())更简单:
在使用tinyurl.com的情况下
import requests
URL = "http://www.google.com/"
r = requests.get("http://tinyurl.com/" + "api-create.php?url=" + URL)
print(r.text)https://stackoverflow.com/questions/43403954
复制相似问题