长网址转短网址

长网址转短网址

准备工作

获取新浪API及其API的source

环境

1. Python3.7

2. requests

3. json

4. tkinter(不做UI可不要)

核心

https://api.t.sina.com.cn/short_url/shorten.json?source=XXXXX&url_long=XXXXX

返回值

[{"url_short":"http://t.cn/EyGscwA","url_long":"https://www.tomtony.top","type":0}]

结合tkinter做个简单的UI

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
import requests
import json
from tkinter import *

class Get_url_short():
def __init__(self):
self.source = 2540340328
self.url = 'https://api.t.sina.com.cn/short_url/shorten.json?'

def get_short(self):
try:
url_long = self.tk_url_long.get()
url = self.url + 'source=' + str(self.source) + '&url_long=' + str(url_long)
html = requests.get(url)
html = html.text
html = json.loads(html)
self.url_short = html[0]['url_short']
Label(text='Short URL:').grid(row=1, column=0)
Label(text=self.url_short).grid(row=1, column=1)
Button(self.short, text="Copy", width=10, command=self.short_copy).grid(row=1, column=2, sticky=W, padx=10, pady=5)
except:
Label(text='请输入带http或https的长链接').grid(row=2, column=1)

def short_copy(self):
try:
self.short.clipboard_clear() # 清除剪贴板内容
self.short.clipboard_append(self.url_short) # 向剪贴板追加内容
Label(text='URL copy succeeded',font=', 10').grid(row=2, column=1)
except:
Label(text='URL copy failed',font=', 10').grid(row=2, column=1)

def short_begin(self):
self.short = Tk()
self.short.title('Short URL')
Label(text='Long URL:').grid(row=0, column=0)
self.tk_url_long = Entry(self.short) # 好友
self.tk_url_long.grid(row=0, column=1)
Button(self.short, text="转化", width=10, command=self.get_short).grid(row=0, column=2, sticky=W, padx=10, pady=5)
mainloop()

if __name__ == '__main__':
short = Get_url_short()
short.short_begin()

成品展示

short_url