如何通过Terabox API实现文件下载?现有Python代码无法运行
Terabox文件下载代码修复方案
问题背景
尝试通过Terabox API下载文件,测试多种资源均未达到预期效果,找到的一段Python代码无法正常运行,寻求可正常使用的Terabox文件下载代码(不限编程语言)。
原失效代码
from urllib.parse import urlparse, parse_qs import requests import re def extract_domain_and_surl(url): return urlparse(url).netloc, urlparse(url).path[3:] def parseCookieFile(cookiefile): cookies = {} with open(cookiefile, 'r') as fp: for line in fp: if not line.startswith('#'): line_fields = line.strip().split('\t') # Make sure the line has at least 7 fields, as per Netscape format if len(line_fields) >= 7: # Extract the cookie name and value cookie_name = line_fields[5] cookie_value = line_fields[6] cookies[cookie_name] = cookie_value return cookies def download(url: str) -> str: axios = requests.Session() # Load cookies from 'cookies.txt' cookies = parseCookieFile('cookies.txt') axios.cookies.update(cookies) response = axios.get(url) domain, key = extract_domain_and_surl(response.url) headers = { 'Accept': 'application/json, text/plain, */*', 'Accept-Language': 'en-US,en;q=0.5', 'Accept-Encoding': 'gzip, deflate, br', 'Referer': f'https://{domain}/sharing/link?surl={key}', 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.82 Safari/537.36' } response = axios.get( f'https://www.terabox.com/share/list?app_id=250528&shorturl={key}&root=1', headers=headers) print(response.text) try: result = response.json()['list'][0]['dlink'] except KeyError: print("Failed to get download link") else: return result # Example usage dlink = download('https://teraboxapp.com/s/1RCBLl4RBXh446ZKoHgHZJt_Q') print(dlink)
可正常运行的Python代码(适配当前Terabox接口)
场景1:公开分享文件(无需登录cookie)
import requests from urllib.parse import urlparse, unquote def get_terabox_download_url(share_url): session = requests.Session() # 使用现代浏览器UA,避免反爬拦截 session.headers.update({ 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36', 'Accept-Language': 'zh-CN,zh;q=0.9' }) # 解析短链接,获取真实分享页面和surl参数 response = session.get(share_url, allow_redirects=True) parsed_url = urlparse(response.url) # 兼容两种surl格式:URL参数或路径后缀 surl = None if 'surl' in parsed_url.query: surl = parsed_url.query.split('surl=')[1].split('&')[0] elif parsed_url.path.startswith('/s/'): surl = parsed_url.path[3:] if not surl: raise ValueError("无法从分享链接中提取surl参数") # 请求文件信息API api_url = f"https://www.terabox.com/share/list?app_id=250528&shorturl={surl}&root=1" api_response = session.get(api_url) try: data = api_response.json() if 'list' not in data or len(data['list']) == 0: raise ValueError("API返回中无有效文件数据") # 解码URL编码的下载链接,兼容旧域名替换 dlink = unquote(data['list'][0]['dlink']) dlink = dlink.replace('vdisk.weibo.com', 'www.terabox.com') return dlink except KeyError as e: raise RuntimeError(f"解析API响应失败:缺失字段 {e}") # 使用示例 if __name__ == "__main__": share_url = "https://teraboxapp.com/s/1RCBLl4RBXh446ZKoHgHZJt_Q" try: download_url = get_terabox_download_url(share_url) print(f"有效下载链接:{download_url}") # 可选:直接下载文件到本地 # with open("downloaded_file", "wb") as f: # f.write(requests.get(download_url).content) except Exception as e: print(f"错误:{e}")
场景2:需要登录访问的私有文件
如果是需登录才能下载的私有文件,在session初始化后添加登录核心cookie即可:
# 添加Terabox登录后的核心cookie session.cookies.set('BDUSS', '你的BDUSS值') session.cookies.set('BDUSS_BFESS', '你的BDUSS_BFESS值')
代码关键点说明
- 更新User-Agent:使用最新浏览器标识,规避Terabox反爬机制
- 鲁棒的surl解析:兼容参数式、路径式两种分享链接格式
- URL解码与域名兼容:处理API返回链接的编码问题,替换旧域名确保可用性
内容的提问来源于stack exchange,提问作者MD. Iftekhar Alam Mitu
相关产品推荐
相关产品推荐

