我想从下载链接下载.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库)
答案 0 :(得分:0)
将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。如果网站拒绝您的自定义用户代理,您可以发送普通浏览器生成的用户代理,例如fake_useragent.UserAgent().random
。