Python
22 Feb 2010
 
 
 
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
# -*- coding: cp1251 -*-
import time
import http.client, urllib.request, re, logging,urllib.parse
def main():
# тестим
key= '123123123'
fn= 'captcha.jpeg'
# отправляем капчу
cap_id= send_cap(key, fn)
if not cap_id:
print ('Не отправилось')
# получаем результат
text= get_cap_text(key, cap_id)
print (text)
def get_cap_text(key, cap_id):
''' Ожидаем и получаем текст капчи '''
logging.info('--- Get captcha text')
time.sleep(5)
# получаем результат
res_url= 'http://antigate.com/res.php'
res_url+= "?" + urllib.parse.urlencode({'key': key, 'action': 'get', 'id': cap_id})
while 1:
res= urllib.request.urlopen(res_url).read()
if res == 'CAPCHA_NOT_READY':
time.sleep(1)
continue
break
res= res.split('|')
if len(res) == 2:
return tuple(res)
else:
return ('ERROR', res[0])
def send_cap(key, fn):
''' Отправляем капчу на anti-capcha.com
Вход:
key - ключ на антикапче
fn - файл с капчей
Выход:
id капчи - в случае успеха
False - неудача
'''
logging.info('--- Send captcha')
data = open(fn, 'rb').read()
# разделитель для данных
boundary= '----------OmNaOmNaOmNamo'
# тело HTTP-запроса
body = '''--%s
Content-Disposition: form-data; name="method"
post
--%s
Content-Disposition: form-data; name="key"
%s
--%s
Content-Disposition: form-data; name="file"; filename="capcha.jpg"
Content-Type: image/pjpeg
%s
--%s--
''' % (boundary, boundary, key, boundary, data, boundary)
# заголовки HTTP-запроса
headers = {'Content-type' : 'multipart/form-data; boundary=%s' % boundary}
# подключение к HTTP-серверу
h = http.client.HTTPConnection('antigate.com')
# посылка запроса
h.request("POST", "/in.php", body, headers)
# получение и анализ ответа HTTP-сервера
resp = h.getresponse()
data = resp.read()
h.close()
if resp.status == 200:
cap_id = re.search('\d+',str(data))
return cap_id.group(0)
else:
logging.error('Captcha not send: %s %s' % (resp.status, resp.reason))
return False
if __name__ == "__main__":
main()