本文目录导读:

是的,完全可以!而且实现起来并不复杂,这里我为你准备了一个 一键生成短链接的实用Python脚本,支持多种免费/付费方案。
基于百度短网址API(推荐,稳定免费)
这是百度官方提供的免费服务,不需要自己部署服务器,有每日调用限额(通常个人使用足够)。
脚本代码
import requests
import json
def generate_baidu_short_url(long_url):
"""
通过百度短网址API生成短链接
"""
api_url = "https://dwz.cn/admin/v2/create"
token = "你的百度短网址Token" # ← 需要替换为你的Token
headers = {
"Content-Type": "application/json",
"Token": token
}
data = {
"Url": long_url
}
try:
response = requests.post(api_url, headers=headers, json=data, timeout=5)
result = response.json()
if result.get("Code") == 0: # 成功
short_url = result.get("ShortUrl")
print(f"✅ 长链接: {long_url}")
print(f"🔗 短链接: {short_url}")
return short_url
else:
print(f"❌ 失败: {result.get('ErrMsg', '未知错误')}")
return None
except Exception as e:
print(f"❌ 请求异常: {str(e)}")
return None
if __name__ == "__main__":
# 使用示例
test_url = "https://www.example.com/very-long-path/with-many-parameters?foo=bar&baz=qux"
generate_baidu_short_url(test_url)
如何获取Token
- 访问 百度短网址官网
- 注册/登录后进入「控制台」→「API管理」
- 复制你的API Token
自建短链服务(完全免费,无需外部API)
使用Python + Flask + SQLite,完全本地运行,零成本。
服务端代码 (server.py)
from flask import Flask, request, redirect, jsonify
import hashlib
import sqlite3
import string
import random
app = Flask(__name__)
DB_NAME = "short_links.db"
def init_db():
"""初始化数据库"""
conn = sqlite3.connect(DB_NAME)
c = conn.cursor()
c.execute('''CREATE TABLE IF NOT EXISTS urls
(id INTEGER PRIMARY KEY AUTOINCREMENT,
short_code TEXT UNIQUE,
long_url TEXT)''')
conn.commit()
conn.close()
def generate_code(long_url):
"""基于URL生成唯一短码"""
hash_obj = hashlib.md5(long_url.encode())
hash_hex = hash_obj.hexdigest()
# 取前6个字符作为短码
return hash_hex[:6]
@app.route('/shorten', methods=['POST'])
def shorten():
"""生成短链接接口"""
data = request.get_json()
long_url = data.get('url')
if not long_url:
return jsonify({"error": "缺少URL参数"}), 400
short_code = generate_code(long_url)
conn = sqlite3.connect(DB_NAME)
c = conn.cursor()
# 检查是否已存在
c.execute("SELECT long_url FROM urls WHERE short_code=?", (short_code,))
existing = c.fetchone()
if existing and existing[0] != long_url:
# 冲突处理:追加随机字符
short_code = short_code + random.choice(string.ascii_lowercase)
# 保存到数据库
c.execute("INSERT OR IGNORE INTO urls (short_code, long_url) VALUES (?, ?)",
(short_code, long_url))
conn.commit()
conn.close()
short_url = f"http://localhost:5000/{short_code}"
return jsonify({"short_url": short_url}), 201
@app.route('/<short_code>')
def redirect_to_long(short_code):
"""短链接重定向"""
conn = sqlite3.connect(DB_NAME)
c = conn.cursor()
c.execute("SELECT long_url FROM urls WHERE short_code=?", (short_code,))
result = c.fetchone()
conn.close()
if result:
return redirect(result[0])
else:
return "短链接不存在", 404
if __name__ == '__main__':
init_db()
app.run(debug=True, port=5000)
客户端调用脚本
import requests
def create_short_url(long_url):
"""调用自建服务生成短链接"""
api_url = "http://localhost:5000/shorten"
response = requests.post(api_url, json={"url": long_url})
if response.status_code == 201:
result = response.json()
print(f"📌 生成的短链接: {result['short_url']}")
return result['short_url']
else:
print(f"❌ 生成失败: {response.text}")
return None
if __name__ == "__main__":
# 测试
from datetime import datetime
test_url = f"https://example.com/article/{datetime.now().timestamp()}"
short = create_short_url(test_url)
运行方式:
# 先启动服务 python server.py # 在另一个终端运行客户端,或直接调用API python client.py
纯前端无服务器方案(最轻量)
使用 新浪短网址API(免费,但不太稳定),或者 is.gd/tinyurl 等第三方开源接口。
一键脚本
import requests
import re
def generate_short_url_via_service(long_url, service="isgd"):
"""
使用第三方服务生成短链接
支持的service: 'isgd', 'tinyurl', 'vgd'
"""
service_map = {
"isgd": f"https://is.gd/create.php?format=simple&url={long_url}",
"tinyurl": f"https://tinyurl.com/api-create.php?url={long_url}",
"vgd": f"https://v.gd/create.php?format=simple&url={long_url}"
}
url = service_map.get(service)
if not url:
print("不支持的服务")
return None
try:
response = requests.get(url, timeout=5)
if response.status_code == 200:
short_url = response.text.strip()
print(f"✅ [{service}] {long_url} → {short_url}")
return short_url
else:
print(f"❌ 失败: {response.status_code}")
return None
except Exception as e:
print(f"❌ 请求异常: {str(e)}")
return None
# 批量生成示例
if __name__ == "__main__":
urls_to_shorten = [
"https://www.python.org/",
"https://github.com/",
"https://stackoverflow.com/questions/ask"
]
for url in urls_to_shorten:
generate_short_url_via_service(url, service="tinyurl")
print("-" * 40)
运行演示输出:
✅ [tinyurl] https://www.python.org/ → https://tinyurl.com/y7v8a123
----------------------------------------
✅ [tinyurl] https://github.com/ → https://tinyurl.com/y9z5b456
----------------------------------------
✅ [tinyurl] https://stackoverflow.com/questions/ask → https://tinyurl.com/y1x3c789
----------------------------------------
推荐使用哪个方案?
| 方案 | 优点 | 缺点 | 推荐场景 |
|---|---|---|---|
| 百度API | 稳定、快速、可管理 | 需要注册账号、有每日限额 | 日常个人使用 |
| 自建服务 | 完全免费、无限制、可自定义 | 需要运行服务器、需要公网IP | 企业内部使用 |
| 第三方API | 最简单、无需注册 | 速度慢、不稳定、可能被墙 | 临时应急使用 |
建议优先使用百度短网址方案,注册一次后长期免费使用,稳定性有保障。
如果需要我帮你生成具体的脚本文件或添加批量处理、CSV导出等功能,可以告诉我你的具体使用场景!