python - 如何将自定义标头添加到 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 参数,但是有什么方法可以添加它吗?我宁愿不逐行实现标题,因为有很多。
任何帮助表示赞赏
解决方案
你真的应该使用requests
这种类型的工作。它使生活更轻松。
https://requests.readthedocs.io/en/master/user/quickstart/#custom-headers
推荐阅读
- python - 如何在python中捕获异常消息?
- wpf - 如何在 MahApps.Metro.Controls 窗体的子窗口中添加 WPF Web 浏览器
- python - 我正在尝试使用 python 3 而不是 python 2
- reactjs - React.js:useState Hook Setter 没有更新状态
- python - Django/Wagtail - 自定义表单小部件 CSS/JS 媒体未使用模板文件呈现
- regex - 仅当指定的字符出现一次时才匹配的正则表达式
- node.js - 上传文档或图像以及其他表单字段 node express
- excel - MS Excel 在 Google 表格中替代 ={A:A} 公式
- flutter - 如何在 wrap 小部件中填充内容?
- javascript - 在没有任何消息的情况下清除 javascript 中的控制台