Python:下载zip文件而不从直接链接提取

2024-06-26 09:52:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试制作一个脚本,用于从直接链接下载文件(例如:http://beatsaver.com/api/download/key/f55c)使用Python脚本。 我在这里或其他网站上尝试过各种代码,要么最终导致zip文件损坏,要么导致“zipfile.BadZipFile:file不是zip文件”

我试过这个:(拉链坏了)

url = "http://beatsaver.com/api/download/key/f55c"
resp = requests.get(url)
zname = os.path.join('BeatSong', "song_test.zip")
zfile = open(zname, 'wb')
zfile.write(resp.content)
zfile.close()

或者3或4个变体:(raise:“zipfile.BadZipFile:文件不是zip文件”)

url = "http://beatsaver.com/api/download/key/f55c"
resp = requests.get(url)
zip = zipfile.ZipFile(io.BytesIO(resp.content))
zip.extractall("/BeatSong")

该链接在加载时自动下载zip 有什么方法可以像从浏览器下载zip文件一样检索zip文件? 谢谢


Tags: 文件key脚本comapihttpurl链接
1条回答
网友
1楼 · 发布于 2024-06-26 09:52:46

首先,在尝试使用python获取url时,url返回403禁止的错误。该网站拒绝向您发送该文件,因为它知道您是一个机器人。我可以通过设置用户代理来克服这个问题

import urllib.request

url = "http://beatsaver.com/api/download/key/f55c"

#add headers so you don't get a 403 error
opener = urllib.request.build_opener()
opener.addheaders = [('user-agent', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36')]
urllib.request.install_opener(opener)

urllib.request.urlretrieve(url, 'song.zip', )

相关问题 更多 >