如何在 python 中使用 urllib 下载 .torrent 文件?

How to download .torrent file using urllib in python?

我想从下载 link 下载 .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

哪里出错了?有没有办法使用磁铁 links? (仅限 urllib 库)

添加 User-Agent http header 作为 @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. If the site rejects your custom User-Agent, you could send User-Agent produced by ordinary browsers such as fake_useragent.UserAgent().random