我有一个大约 3,000 个 URL 的列表,我正在尝试创建 Google 缩短链接,这个想法是这个 CSV 有一个链接列表,我希望我的代码在原始 URL 旁边的列中输出缩短的链接.
我一直在尝试修改此网站此处上找到的代码,但我不够熟练,无法使其正常工作。
这是我的代码(我通常不会发布 API 密钥,但最初提出这个问题的人已经在该网站上公开发布了它):
import json
import pandas as pd
df = pd.read_csv('Links_Test.csv')
def shorternUrl(my_URL):
API_KEY = "AIzaSyCvhcU63u5OTnUsdYaCFtDkcutNm6lIEpw"
apiUrl = 'https://www.googleapis.com/urlshortener/v1/url'
longUrl = my_URL
headers = {"Content-type": "application/json"}
data = {"longUrl": longUrl}
h = httplib2.Http('.cache')
headers, response = h.request(apiUrl, "POST", json.dumps(data), headers)
return response
for url in df['URL']:
x = shorternUrl(url)
# Then I want it to write x into the column next to the original URL
但在我开始弄清楚如何将新 URL 写入 CSV 文件之前,我只在此时出现错误。
这是一些示例数据:
URL
www.apple.com
www.google.com
www.microsoft.com
www.linux.org
我认为问题在于您没有在请求中包含 API 密钥。顺便说一下,
certifi
包允许您保护与链接的连接。您可以使用 pip install certifi
或 pip urllib3[secure]
来获取它。
这里我创建了自己的 API 密钥,因此您可能需要将其替换为您的。
from urllib3 import PoolManager
import json
import certifi
sampleURL = 'http://www.apple.com'
APIkey = 'AIzaSyD8F41CL3nJBpEf0avqdQELKO2n962VXpA'
APIurl = 'https://www.googleapis.com/urlshortener/v1/url?key=' + APIkey
http = PoolManager(cert_reqs = 'CERT_REQUIRED', ca_certs=certifi.where())
def shortenURL(url):
data = {'key': APIkey, 'longUrl' : url}
response = http.request("POST", APIurl, body=json.dumps(data), headers= {'Content-Type' : 'application/json'}).data.decode('utf-8')
r = json.loads(response)
return (r['id'])
解码部分将响应对象转换为字符串,以便我们可以将其转换为 JSON 并检索数据。
从那里开始,您可以将数据存储到另一列中,依此类推。
对于sampleUrl,我从函数中返回了https(
goo.gl/nujb
)。
我在这里找到了解决方案:
https://pypi.python.org/pypi/pyshorteners
从链接页面复制的示例:
from pyshorteners import Shortener
url = 'http://www.google.com'
api_key = 'YOUR_API_KEY'
shortener = Shortener('Google', api_key=api_key)
print "My short url is {}".format(shortener.short(url))