如何在 python 中使用 urllib 下载 .torrent 文件?
Posted
技术标签:
【中文标题】如何在 python 中使用 urllib 下载 .torrent 文件?【英文标题】:How to download .torrent file using urllib in python? 【发布时间】:2016-05-12 08:33:45 【问题描述】:我想从下载链接下载 .torrent 文件。我希望将上述文件以 .torrent 格式保存在项目文件夹中 我试过下面的代码
import urllib.request
url = 'https://torcache.net/torrent/92B4D5EA2D21BC2692A2CB1E5B9FBECD489863EC.torrent?title=[kat.cr]avengers.age.of.ultron.2015.1080p.brrip.x264.yify'
def download_torrent(url):
name= "movie"
full_name = str(name) + ".torrent"
urllib.request.urlretrieve(url, full_name)
download_torrent(url)
它显示以下错误:
Traceback (most recent call last):
File "/home/taarush/PycharmProjects/untitled/fkn.py", line 10, in <module>
download_torrent(url)
File "/home/taarush/PycharmProjects/untitled/fkn.py", line 7, in download_torrent
urllib.request.urlretrieve(url, full_name)
File "/usr/lib/python3.5/urllib/request.py", line 187, in urlretrieve
with contextlib.closing(urlopen(url, data)) as fp:
File "/usr/lib/python3.5/urllib/request.py", line 162, in urlopen
return opener.open(url, data, timeout)
File "/usr/lib/python3.5/urllib/request.py", line 465, in open
response = self._open(req, data)
File "/usr/lib/python3.5/urllib/request.py", line 483, in _open
'_open', req)
File "/usr/lib/python3.5/urllib/request.py", line 443, in _call_chain
result = func(*args)
File "/usr/lib/python3.5/urllib/request.py", line 1286, in https_open
context=self._context, check_hostname=self._check_hostname)
File "/usr/lib/python3.5/urllib/request.py", line 1246, in do_open
r = h.getresponse()
File "/usr/lib/python3.5/http/client.py", line 1197, in getresponse
response.begin()
File "/usr/lib/python3.5/http/client.py", line 297, in begin
version, status, reason = self._read_status()
File "/usr/lib/python3.5/http/client.py", line 266, in _read_status
raise RemoteDisconnected("Remote end closed connection without"
http.client.RemoteDisconnected: Remote end closed connection without response
哪里出错了?有没有办法使用磁力链接? (仅限 urllib 库)
【问题讨论】:
您很可能需要提供额外的标头,例如 User-Agent 和其他标头,以便您的请求看起来像是由浏览器发出的 @Alik ***.com/questions/802134/… 。这个问题很有帮助,但我不明白应该在代码中的何处添加标题。 【参考方案1】:将 User-Agent http 标头添加为 @Alik suggested。 The question you've linked 展示了如何。这是对 Python 3 的改编:
#!/usr/bin/env python3
import urllib.request
opener = urllib.request.build_opener()
opener.addheaders = [('User-Agent', 'CERN-LineMode/2.15 libwww/2.17b3')]
urllib.request.install_opener(opener) #NOTE: global for the process
urllib.request.urlretrieve(url, filename)
见the specification for User-Agent。如果站点拒绝了你自定义的 User-Agent,你可以发送普通浏览器生成的 User-Agent,如fake_useragent.UserAgent().random
。
【讨论】:
以上是关于如何在 python 中使用 urllib 下载 .torrent 文件?的主要内容,如果未能解决你的问题,请参考以下文章