闲着没事,写了个小爬虫,爬了5万多BT种子。
5万多种子有近3个G的大小,开打文件夹巨卡,就想把种子转成磁力,这样,5万多种子也就一个TXT文件就可以存下了。
先网上找找别人是怎么干的,
发现都是用bencode这个模块。例子也有,但都是python2.7的,模块本身也只支持python2.7.
使用bencode模块的例子如下:
import bencode
import sys
import hashlib
import base64#读取种子文件
torrent = open(torrentName, 'rb').read()
#计算meta数据
metadata = bencode.bdecode(torrent)
hashcontents = bencode.bencode(metadata['info'])
digest = hashlib.sha1(hashcontents).digest()
b32hash = base64.b32encode(digest)
#打印
print 'magnet:?xt=urn:btih:%s' % b32hash
是不是很简单。。可我用的是Python3哇,也不想学python2.7
先试了试,直接bencode出错,网上有一两个贴子说可以改模块代码,我试了,没改成。。还是不行
还是看自己的,先去pypi上看bencode有没有更新,发现有一个bencode.py的模块,据说就是bencode的高级版,4.0 版本还支持Python3, 下来试试,
先复制上面的代码。做些修改,把bencode改成bencodepy。。。
这么简单就行,现实果然是残酷的,直接就报错了
在出错的前行加个print看看上步得到了个啥,
在
hashcontents = bencodepy.bencode(metadata['info'])
前加一行
print(metadata)
运行,
在错误前多了一行,看样子metdata是个字典,把字典都打出来看看,加下面几行
for key in metadata.keys():print(key,metadata[key])
运行
字典都打出来了,有一个key是info但前面有个b,那肯定是编码的问题,先把b搞掉。。用encode
弄个新字典,把搞掉b的key当新字典的k,后面值前面的b先不管。。
import bencodepy
import hashlib
import base64#目录下扔个种子试试,
torrentName = 'ubuntu-16.04.6-desktop-i386.iso.torrent'#读取种子文件
torrent = open(torrentName, 'rb').read()
#计算meta数据
metadata = bencodepy.bdecode(torrent)#新加的部份,新建个字典,把原字典的key解码,存到新字典里
metadata1 ={}
for key in metadata.keys():key1 =key.decode("utf-8")metadata1[key1]=metadata[key]hashcontents = bencodepy.bencode(metadata1['info'])#把原来的metadata改成新字典metadata1
digest = hashlib.sha1(hashcontents).digest()
b32hash = base64.b32encode(digest)
#打印
print('magnet:?xt=urn:btih:%s' % b32hash )
运行
成了?不对,磁力链里还有个b,先手动把b''去掉,得到地址是
magnet:?xt=urn:btih:YFTZNJ2NYJGMPRW7F55WNODB4IW6Y2NR
打开XL,直接跳到下载了,居然可以下,哈,成了,看来只要把这个b搞掉就好了,
加decode就好,完工。。
最终代码。
import bencodepy
import hashlib
import base64#目录下扔个种子试试,
torrentName = 'ubuntu-16.04.6-desktop-i386.iso.torrent'#读取种子文件
torrent = open(torrentName, 'rb').read()
#计算meta数据
metadata = bencodepy.bdecode(torrent)#新加的部份,新建个字典,把原字典的key解码,存到新字典里
metadata1 ={}
for key in metadata.keys():key1 =key.decode("utf-8")metadata1[key1]=metadata[key]hashcontents = bencodepy.bencode(metadata1['info'])#把原来的metadata改成新字典metadata1
digest = hashlib.sha1(hashcontents).digest()
b32hash = base64.b32encode(digest).decode("utf-8")#加decode解码
#打印
print('magnet:?xt=urn:btih:%s' % b32hash )