如何通过请求下载文件而不是HTML

时间:2019-07-20 10:16:11

标签: python python-requests

好的,所以我决定要一个程序根据地图号下载osu地图(因为缺少更好的术语)。在对链接进行了一些测试以了解重定向之后,我得到了一个进入.../download页面的程序-当我进入该页面时,地图将下载。但是,当尝试通过请求下载它时,我得到了HTML。

    def grab(self, identifier=None):
        if not identifier:
            print("Missing Argument: 'identifier'")
            return
        mapLink = f"https://osu.ppy.sh/beatmaps/{identifier}"
        dl = requests.get(mapLink, allow_redirects=True)
        if not dl:
            print("Error: map not found!")
            return
        mapLink2 = dl.url 
        mapLink2 = f"https://osu.ppy.sh/beatmapsets/{self.parseLink(mapLink2)}/download"
        dl = requests.get(mapLink2)

        with open(f"{identifier}.osz", "wb") as f:
            f.write(dl.content)

如果有必要,这里是self.parseLink


    def parseLink(self, mapLink=None):
        if not mapLink:
            return None
        id = mapLink.replace("https://osu.ppy.sh/beatmapsets/","")
        id = id.split("#")
        return id[0]

理想情况下,当我在grab()的末尾打开文件时,它应该保存一个可用的.osz文件-不是html的文件,可以将其拖动到实际游戏中并使用。当然,这在我的测试中还处于极早的阶段,为了方便起见,我将找出一种将文件名设为歌曲名的方法。

编辑:identifier的示例是:OsuMaps().grab("1385415"),以防您要测试

1 个答案:

答案 0 :(得分:0)

有一个非常快速的解决方法:

  • 需要登录
  • 需要特定的元素

此解决方法以https://bloodcat.com/osu/的形式出现-要直接获得指向地图的下载链接,您需要的是:https://bloodcat.com/osu/s/<beatmap set number>

这里是一个例子:

id = "653534" # this map is ILY - Panda Eyes 
mapLink = f"https://bloodcat.com/osu/s/{id}" # adds id to the link
dl = requests.get(mapLink)
if len(dl.content) > 330: # see below for explanation
    with open(f"{lines[i].rstrip()}.osz", "wb") as f:
    f.write(dl.content)
else:
    print("Map doesn't exist")

if len(dl.conetent) > 330行是我解决链接无效的解决方法。 .osz文件可以包含成千上万行未知字符,而站点的“未找到”页面少于330行-我们可以使用它来检查文件是否太短以至于不能成为节拍图。

仅此而已!随意使用代码。

相关问题