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



我想从下载链接下载.torrent文件。我希望上述文件以.trent格式保存在项目文件夹中我已经尝试了以下代码

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库)

按照@Alik的建议添加用户代理http头。你链接的问题显示了如何操作。以下是对Python3:的改编

#!/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)

请参阅用户代理的规范。如果网站拒绝您的自定义用户代理,您可以发送由fake_useragent.UserAgent().random等普通浏览器生成的用户代理。

最新更新