usr = 'xx' psw = 'oo'
resp = urllib2.urlopen('https://login.sina.com.cn/sso/login.php?username=%s&password=%s&returntype=TEXT' %
( usr, psw)) cookie = Cookie.SimpleCookie(resp.headers['set-cookie']) headers = { 'Referer': 'http://t.sina.com.cn', 'Cookie': cookie_header(cookie),
'User-Agent': 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.2.3pre) Gecko/20100405 Firefox/3.6.3plugin1', } def cookie_header(cookie):
ret = '' for v in cookie.values(): ret += "%s=%s; " % (v.key, v.value) return ret
headers就是后续的请求中,需要传递的参数了。
取回一些验证码样本:
for i in xrange(100):
req_img = urllib2.Request('http://t.sina.com.cn/pincode/pin.php?lang=zh&r=%d&rule' % int(time() * 1000),
headers = headers) res_img = urllib2.urlopen(req_img) f = open('xinlang_pincode/%d.png' % i, 'wb') f.write(res_img.read()) f.close()
file = open('xinlang.img', 'a') for c in chars: nstr = '' im_loaded = c.load() for x in range(20): for y in range(20): if im_loaded[x, y] == 255:
nstr += '0' else: nstr += '1' c.show() n = raw_input('? ') file.write(nstr+':'+n+'\n') file.close()
这里的特征,就是直接把每一个像素的信息,用0和1组成的字符串表示。
训练的结果是一个文本文件,记录了对应的特征和字符,用于下面的比对。
比对函数:
pattern = [] for l in open('xinlang.img', 'r').read().split('\n'): pattern.append(l.split(':')) del pattern[-1] def what(img): im = img.load() nstr = ''
for x in xrange(20): #生成目标图像的特征字符串 for y in xrange(20): if im[x, y] == 255: nstr += '0' else: nstr += '1' minmin = 400
res = None for p in pattern: cur = 0 for i in xrange(400):
if nstr[i] != p[0][i]: #比对每一个像素,如果不相同,则增加差异值 cur += 1 if cur < = minmin: #记录下差异值最小时所对应的字符
minmin = cur res = p[1] return res