首页 > 解决方案 > 如何将自定义标头添加到 urllib 请求?

问题描述

我查看了 urllib 模块上的文档,但是,当我尝试下载文件时,我不太明白如何将标头添加到请求中。

我习惯使用 requests 模块,但是,这对我来说不是一个可行的解决方案,因为它根本不下载任何东西。

Headers = {'Connection': 'keep-alive'}

index_name = 'Index.m3u8'
Videoindex = 'http://test.com/notreal.ts'

indexresponse = urllib.request.urlopen(Videoindex, headers=Headers)
with open(index_name,'wb') as x:
    x.write(indexresponse.read())

audio_name = 'Audio.m3u8'
Audioindex = 'http://test.com/notreal.aac'

audioresponse = urllib.request.urlopen(Audioindex, headers=Headers)
with open(audio_name,'wb') as y:
    y.write(audioresponse.read())

我知道您无法解析 urlopen 中的 header 参数,但是有什么方法可以添加它吗?我宁愿不逐行实现标题,因为有很多。

任何帮助表示赞赏

标签: pythonurllib

解决方案


你真的应该使用requests这种类型的工作。它使生活更轻松。

https://requests.readthedocs.io/en/master/user/quickstart/#custom-headers


推荐阅读