コード例 #1
0
ファイル: ecc.py プロジェクト: re1ard/ecc
class anticaptcha:
	gate = None
	processing = False

	def __init__(self,agkey):
		self.gate = AntiGate(agkey)
		print 'good shit'
		print 'antigate balance: ' + str(self.gate.balance())
		return None

	def captchasolution(self,error):
		link = "./captcha_directory/"+str(time.time())+".jpg"
		urllib.urlretrieve(error.get_url(), link)
		print 'captcha loaded to directory: ' + link
		sid = self.gate.send(link)
		print 'done... lets begin to solution'
		key = self.gate.get(sid)
		print 'ok... this code: ' + key
		os.rename("./captcha_directory/"+key+".jpg")
		return key

	def solution(self,error):
		if self.processing:
			while self.processing:
				time.sleep(3)
			return True,0
			
		else:
			self.processing = True
			id = error.try_again(self.captchasolution(error))
			self.processing = False
			return False,id
コード例 #2
0
def error_happens(response, current, params):
    print "===================ERROR=============================="
    print response
    print "===================ERROR END=========================="
    response = response['error']
    if response['error_code'] == 14: #Captcha needed
        os.popen("curl '%s' > captcha1.jpg" %response['captcha_img'])
        gate = AntiGate(config.ANTICAPCHA_KEY, auto_run=False)
        captcha1 = gate.send('captcha1.jpg')
        captcha =  gate.get(captcha1)
        print captcha
        time.sleep(90.0)
        # print "Введи капчу!"
        # captcha = sys.stdin.readline()
        # captcha = captcha.split('\n')[0]
        # print captcha
        params += [('captcha_sid ', response['captcha_sid']), ('captcha_key', captcha)]
        method = ''
        for para in response['request_params']:
            if para['key'] == 'method':
                method = para['value']
            else:
                pass
        r = call_api(method, params, current['token'])
        print r
        return r
    else:
        print "Дело не в капче!\n", response['error_msg']
        return 
コード例 #3
0
    def test_manual_binary(self):
        gate = AntiGate(API_KEY, auto_run=False)

        captcha_id = gate.send(open(IMAGE1, 'rb').read(), binary=True)
        self.assertTrue(str(captcha_id).isdigit())

        captcha_value = gate.get(captcha_id)
        self.assertEqual(str(captcha_value), '123')
コード例 #4
0
ファイル: test_cases.py プロジェクト: luis-wang/antigate
    def test_manual(self):
        gate = AntiGate(API_KEY, auto_run=False)

        captcha_id = gate.send(IMAGE1)
        self.assertTrue(str(captcha_id).isdigit())

        captcha_value = gate.get(captcha_id)
        self.assertEqual(str(captcha_value), '123')
コード例 #5
0
ファイル: test_cases.py プロジェクト: Lokosia/antigate
    def test_manual_binary(self):
        gate = AntiGate(API_KEY, auto_run=False)

        captcha_id = gate.send(open(IMAGE1, 'rb').read(), binary=True)
        self.assertTrue(str(captcha_id).isdigit())

        captcha_value = gate.get(captcha_id)
        self.assertEqual(str(captcha_value), '123')
コード例 #6
0
ファイル: test_cases.py プロジェクト: kostyll/antigate
    def test_manual(self):
        gate = AntiGate(API_KEY, auto_run=False)

        captcha_id = gate.send(IMAGE1)
        self.assertTrue(str(captcha_id).isdigit())

        captcha_value = gate.get(captcha_id)
        self.assertEqual(str(captcha_value), '123')
コード例 #7
0
ファイル: test_cases.py プロジェクト: luis-wang/antigate
    def test_manual_base64(self):
        gate = AntiGate(API_KEY, auto_run=False)
        fp = open(IMAGE1, 'rb')
        captcha_id = gate.send(fp.read())
        self.assertTrue(str(captcha_id).isdigit())
        fp.close()

        captcha_value = gate.get(captcha_id)
        self.assertEqual(str(captcha_value), '123')
コード例 #8
0
ファイル: test_cases.py プロジェクト: kostyll/antigate
    def test_manual_base64(self):
        gate = AntiGate(API_KEY, auto_run=False)
        fp = open(IMAGE1, 'rb')
        captcha_id = gate.send(fp.read())
        self.assertTrue(str(captcha_id).isdigit())
        fp.close()

        captcha_value = gate.get(captcha_id)
        self.assertEqual(str(captcha_value), '123')
コード例 #9
0
ファイル: test_cases.py プロジェクト: luis-wang/antigate
    def test_multiple(self):
        gate = AntiGate(API_KEY, auto_run=False)
        captcha_id1 = gate.send(IMAGE1)
        captcha_id2 = gate.send(IMAGE2)

        self.assertTrue(str(captcha_id1).isdigit())
        self.assertTrue(str(captcha_id2).isdigit())

        results = gate.get_multi([captcha_id1, captcha_id2])
        self.assertTrue(results == ['123', '456'])
コード例 #10
0
ファイル: test_cases.py プロジェクト: kostyll/antigate
    def test_multiple(self):
        gate = AntiGate(API_KEY, auto_run=False)
        captcha_id1 = gate.send(IMAGE1)
        captcha_id2 = gate.send(IMAGE2)

        self.assertTrue(str(captcha_id1).isdigit())
        self.assertTrue(str(captcha_id2).isdigit())

        results = gate.get_multi([captcha_id1, captcha_id2])
        self.assertTrue(results == ['123', '456'])
コード例 #11
0
 def captcha_wrapper(self, captcha_image_url):
     if self.anti_key is not None:
         if AntiGate(self.anti_key).balance() > 0:
             response = requests.get(captcha_image_url, stream=True)
             captcha = AntiGate(self.anti_key, response.raw)
             del response
             return str(captcha)
         else:
             logging.error('Anticaptcha error: zero balance')
     else:
         return None
コード例 #12
0
    def test_multiple_binary(self):
        gate = AntiGate(API_KEY, auto_run=False)
        captcha_id1 = gate.send(open(IMAGE1, 'rb').read(), binary=True)
        captcha_id2 = gate.send(open(IMAGE2, 'rb').read(), binary=True)

        self.assertTrue(str(captcha_id1).isdigit())
        self.assertTrue(str(captcha_id2).isdigit())

        results = gate.get_multi([captcha_id1, captcha_id2])

        #self.assertListEqual(results, ['123', '456'])
        self.assertTrue(results == ['123', '456'])
コード例 #13
0
ファイル: test_cases.py プロジェクト: Lokosia/antigate
    def test_multiple_binary(self):
        gate = AntiGate(API_KEY, auto_run=False)
        captcha_id1 = gate.send(open(IMAGE1, 'rb').read(), binary=True)
        captcha_id2 = gate.send(open(IMAGE2, 'rb').read(), binary=True)

        self.assertTrue(str(captcha_id1).isdigit())
        self.assertTrue(str(captcha_id2).isdigit())

        results = gate.get_multi([captcha_id1, captcha_id2])

        #self.assertListEqual(results, ['123', '456'])
        self.assertTrue(results == ['123', '456'])
コード例 #14
0
def solve_captcha(img):

    while True:
        try:
            gate = AntiGate(key)
            captcha_id = gate.send(img)
            answer = (gate.get(captcha_id))
            return (answer)

        except AntiGateError as error:
            print(error)
            break
コード例 #15
0
def get_captcha_answer(captcha_url):
    captcha_name = 'captcha.jpg'

    img_data = requests.get(captcha_url).content
    with open(captcha_name, 'wb') as handler:
        handler.write(img_data)

    gate = AntiGate('90f2971a20beee5a508bad796a8790fa')
    captcha_id = gate.send(captcha_name)
    print('Расшифровываем капчу')
    result = gate.get(captcha_id)
    print('Расшифровали капчу: %s' % result)
    return result
コード例 #16
0
ファイル: captcha.py プロジェクト: EugeneRymarev/VKWorker
class AG:
    def __init__(self):
        self.gate = AntiGate(config.ag_key)
        self.answer = ''

    def captcha_solve(self, url):
        with open('image.jpg', 'wb') as image:
            image.write(urlopen(url).read())
        self.answer = self.gate.send('image.jpg')
        return self.gate.get(self.answer)

    def abuse(self):
        self.gate.abuse()
コード例 #17
0
ファイル: test_cases.py プロジェクト: luis-wang/antigate
    def test_multiple_binary(self):
        gate = AntiGate(API_KEY, auto_run=False)
        fp1 = open(IMAGE1, 'rb')
        fp2 = open(IMAGE2, 'rb')
        captcha_id1 = gate.send(fp1.read())
        captcha_id2 = gate.send(fp2.read())
        fp1.close()
        fp2.close()

        self.assertTrue(str(captcha_id1).isdigit())
        self.assertTrue(str(captcha_id2).isdigit())

        results = gate.get_multi([captcha_id1, captcha_id2])
        self.assertTrue(results == ['123', '456'])
コード例 #18
0
ファイル: test_cases.py プロジェクト: kostyll/antigate
    def test_multiple_binary(self):
        gate = AntiGate(API_KEY, auto_run=False)
        fp1 = open(IMAGE1, 'rb')
        fp2 = open(IMAGE2, 'rb')
        captcha_id1 = gate.send(fp1.read())
        captcha_id2 = gate.send(fp2.read())
        fp1.close()
        fp2.close()

        self.assertTrue(str(captcha_id1).isdigit())
        self.assertTrue(str(captcha_id2).isdigit())

        results = gate.get_multi([captcha_id1, captcha_id2])
        self.assertTrue(results == ['123', '456'])
コード例 #19
0
def captcha_handler(captcha):

    config = get_auth()
    api_key = config.get('antigate', 'api_key')

    cap_img = captcha.get_image()
    print('Разгадываю капчу..')

    gate = AntiGate(api_key)
    captcha_id1 = gate.send(cap_img)
    key = gate.get(captcha_id1)
    print('Разгадал! Тут написанно:', key, 'Ввожу..')

    # Пробуем снова отправить запрос с капчей
    return captcha.try_again(key)
コード例 #20
0
ファイル: models.py プロジェクト: muroslav2909/reserv
    def main_func(self):
            pyautogui.click(x=771, y=573)
            is_ok = False
            while is_ok!=True:
                if self.status != STOP:
                    sleep(5)
                    pyautogui.moveTo(x=100, y=100)
                    self.driver.save_screenshot('/home/myroslav/reserv/reserv/visareserv/screenshot/screed/1'+'.png')

                    from PIL import Image
                    test_image = "/home/myroslav/reserv/reserv/visareserv/screenshot/screed/1.png"
                    original = Image.open(test_image)
                    box = (569, 89, 982, 596)
                    cropped_example = original.crop(box)
                    cropped_example.save("/home/myroslav/reserv/reserv/visareserv/screenshot/res/1.png", 'png')

                    from antigate import AntiGate
                    gate = AntiGate('AntiGatePass')
                    captcha_id = gate.send("/home/myroslav/reserv/reserv/visareserv/screenshot/res/1.png")
                    result = gate.get(captcha_id)
                    print result
                    if result:
                        all_number = self.get_number_image(result)
                        print "all_number", all_number
                        coordinate = self.get_coordinate(all_number)
                        print "coordinate", coordinate
                        self.click_on_image(coordinate)
                        pyautogui.click(x=954, y=706)
                        pyautogui.moveTo(710, 657, 3, pyautogui.easeInOutQuad)
                        pyautogui.click(x=710, y=657)

                        text = self.driver.find_element_by_xpath('//*[@id="cp1_lblNoDates"]').text
                        print text
                        print self.driver.find_element_by_xpath('//*[@id="cp1_lblNoDatesEmbassyInfo"]').text
                        #We are sorry, but no free slots are available. Try to register later.
                        # [2016-02-19 00:05:09,402: WARNING/Worker-5] 2/19/2016 12:05:12 AM UTC, Ukraine () - Kyjev, Long-term residence permit

                        if "We are sorry" in text:
                            pyautogui.moveTo(685, 439, 3, pyautogui.easeInOutQuad)
                            pyautogui.click(x=685, y=439)
                            sleep(2)
                            obj = DateCheckerBase(company=self, text=text, free_date=None)
                            obj.save()
                            self.main_func()
                        else:
                            is_ok = True
                            obj = DateCheckerBase(company=self, text=text, free_date=None)
                            obj.save()
コード例 #21
0
 def captcha():
     try:
         img = WebDriverWait(driver, 20).until(
             EC.visibility_of_element_located((By.TAG_NAME, 'img')))
         sleep(1)
         driver.save_screenshot('%i.png' % pid)
         location, size = img.location, img.size
         im = Image.open('%i.png' % pid)  # uses PIL library to open image in memory
         left = location['x']
         top = location['y']
         right = location['x'] + size['width']
         bottom = location['y'] + size['height']
         im = im.crop((left, top, right, bottom))  # defines crop points
         im.save('%i.png' % pid)  # saves new cropped image
         solve = AntiGate(API_KEY, '%i.png' % pid)
         field = WebDriverWait(driver, 10).until(EC.visibility_of_element_located((By.NAME, 'captcha')))
         field.send_keys(solve.captcha_result)
         field.submit()
         return solve
     except TimeoutException:
         log("Timeout exception")
         keywords.put(row)
         return 1
     except AntiGateError:
         log("Antigate Error")
         return 0
コード例 #22
0
 def captcha():
     try:
         img = WebDriverWait(chrome, 20).until(
             ec.visibility_of_element_located(
                 (By.ID, 'recaptcha_challenge_image')))
         sleep(1)
         chrome.save_screenshot('%i.png' % pid)
         location, size = img.location, img.size
         im = Image.open(
             '%i.png' %
             pid)  # uses PIL library to open image in memory
         left = location['x']
         top = location['y'] - 100
         right = location['x'] + 310
         bottom = location['y'] - 35
         im = im.crop(
             (left, top, right, bottom))  # defines crop points
         im.save('%i.png' % pid)  # saves new cropped image
         solution = AntiGate(API_KEY, '%i.png' % pid)
         field = wait.until(
             ec.visibility_of_element_located(
                 (By.ID, 'recaptcha_response_field')))
         field.send_keys(solution.captcha_result)
         field.submit()
         return solution
     except TimeoutException:
         return 0
     except AntiGateError:
         return 1
コード例 #23
0
def solve_captcha(image):
    from antigate import AntiGate, AntiGateError

    sent = False
    while not sent:
        try:
            gate = AntiGate('.')
            captcha_id = gate.send(image)
            answer = (gate.get(captcha_id))
            return (answer)

        except AntiGateError as error:
            import _email
            logger.error('<ERROR: %s>' % error)
            _email.send('CAPTCHA', error, " ")
            break
コード例 #24
0
    def crack(self, num):
        # pick a random number
        print "trying number", num

        response = requests.get(URL)
        result = next(self.site.finditer(response.text), None).group(0)
        response = requests.get(result)
        challenge = next(self.challenge.finditer(response.text), None).group(1)

        file = NamedTemporaryFile(prefix="captcha_")
        response = requests.get(IMAGE + challenge, stream=True)
        for chunk in response.iter_content(1024):
            file.write(chunk)
        file.flush()
        print "waiting for asians"
        decaptched = AntiGate(self.ui.antigateid, file.name)
        print "asians completed, here is your captcha", decaptched

        username = (
            "*****@*****.**" %
            (self.ui.firstname[0].lower(), self.ui.lastname[0].lower(), num)
        )
        response = requests.post(RESETPASS, {
            "action": "resetpass2",
            "ime": self.ui.firstname,
            "priimek": self.ui.lastname,
            "dan": self.ui.date.day,
            "mesec": self.ui.date.month,
            "leto": self.ui.date.year,
            "vpisna": self.ui.studentid,
            "clanica": self.ui.faculty,
            "upn": username,
            "recaptcha_challenge_field": challenge,
            "recaptcha_response_field": str(decaptched)
        })

        if "nastavljeno na" in response.text:
            print "username found"
            return username

        if "podatkov ne najdemo" in response.text:
            print "Wrong username"

        if "Izziva niste" in response.text:
            print "Wrong captcha"
            decaptched.abuse()
            raise Exception("Wrong captcha")
コード例 #25
0
    def __getCaptcha(self, image_file='/tmp/.air_mail.jpeg'):
        if hasattr(self, 'code'):
            return

        self.g.go('http://track-chinapost.com/startairmail.php')
        self.image = self.g.xpath('//img[@id="verifyimg"]').get('src')
        self.cookie = self.g.xpath('//input[@name="cookie"]').get('value')
        self.g.download(self.image, image_file)
        self.gate = AntiGate(self.db['api_key'], image_file)
        self.code = str(self.gate)
コード例 #26
0
    def captcha_send(self, img_bit):
        """
        Принемает картинку ->
        Отправляет её на "анти капчу" ->
        и отдает результат

        :param img_bit: картинка в виде бинарной строки
        :return: результат распознания
        """
        try:
            captcha_gate = AntiGate('35c9e83daa70e28958154736d1621d2e')  # TODO убрать данные
            captcha_id = captcha_gate.send(img_bit)

            captcha = captcha_gate.get(captcha_id)

            logger.info('captcha_gate get: {}'.format(captcha))

            return captcha
        except Exception as err:
            # logger.warning(err)
            return None
コード例 #27
0
ファイル: RegBot.py プロジェクト: ThiccPadx/kons
 def _decodeCaptchaFile(self):
     captchaImage = self._getCaptchaFile()
     try:
         captchaCode = AntiGate(self._ak,
                                captchaImage,
                                grab_config={
                                    'connect_timeout': 30,
                                    'timeout': 60
                                })
     except Exception, e:
         echo(
             str(e).replace('Errno ', 'E-') + ' Try decode captcha again.',
             'ERROR', self.work_dir)
         self.log('error',
                  inspect.stack()[0][3] + ': ' + str(e))
         self.run()
コード例 #28
0
def deleteLike(xfaves,xtype):
    print('Deleting...')
    getOwner = {
        'post': 'to_id',
        'photo': 'owner_id',
        'video': 'owner_id',
    }
    getId = {
        'post': 'id',
        'photo': 'pid',
        'video': 'vid',
    }
    i = 0
    while i < len(xfaves):
        try:
            api.likes.delete(type=xtype, owner_id=str(xfaves[i][getOwner[xtype]]), item_id=xfaves[i][getId[xtype]])
            time.sleep(0.35)
            i += 1
        except vk.exceptions.VkAPIError as e:
            xcaptcha_sid = e.captcha_sid
            xcaptcha_img = e.captcha_img
            p = requests.get(xcaptcha_img)
            out = open("img.jpg", "wb")
            out.write(p.content)
            out.close()
            xcaptcha_text = str(AntiGate(' ', 'img.jpg')) #Ввести ключ антийгет
            try:
                api.likes.delete(type=xtype, owner_id=str(xfaves[i][getOwner[xtype]]), item_id=xfaves[i][getId[xtype]],
                                 captcha_sid=xcaptcha_sid, captcha_key=xcaptcha_text)
                print("Была решена капча: " + xcaptcha_text + ", все в порядке.")
            except vk.exceptions.VkAPIError as e:
                print("Что-то пошло не так, наверно уменьшил время ожидания?")
                i += 1
        except TypeError:
            print("Что-то пошло не так, типы поломались, пробуем перейти к другой закладке")
            i += 1
コード例 #29
0
ファイル: ocr.py プロジェクト: crazydreamer/jobvite2.0
from antigate import AntiGate

config = {'min_len': '3', 'max_len': '4', 'phrase': '1'}
img_path = '/Users/jason/Downloads/image.jpeg'
gate = AntiGate('64192b381a6a42883ee6af1c21bcfa7a', img_path, send_config=config, domain='eve.cm')
print gate
if str(gate) != '210':
	gate.abuse()
print gate.balance()
コード例 #30
0
ファイル: captcha.py プロジェクト: EugeneRymarev/VKWorker
 def __init__(self):
     self.gate = AntiGate(config.ag_key)
     self.answer = ''
コード例 #31
0
ファイル: test_cases.py プロジェクト: luis-wang/antigate
 def test_abuse(self):
     gate = AntiGate(API_KEY, IMAGE1)
     if str(gate) != 'qwerty':
         self.assertTrue(gate.abuse())
コード例 #32
0
 def test_load(self):
     self.assertTrue(len(AntiGate(API_KEY).load()) > 0)
コード例 #33
0
ファイル: test_cases.py プロジェクト: luis-wang/antigate
 def test_load(self):
     load = AntiGate(API_KEY).load()
     self.assertTrue(len(load) > 0)
     self.assertEqual(type(load), OrderedDict)
     self.assertTrue(load.get('load') is not None)
コード例 #34
0
ファイル: test_cases.py プロジェクト: kostyll/antigate
 def test_abuse(self):
     gate = AntiGate(API_KEY, IMAGE1)
     if str(gate) != 'qwerty':
         self.assertTrue(gate.abuse())
コード例 #35
0
ファイル: test_cases.py プロジェクト: luis-wang/antigate
 def test_balance(self):
     balance = AntiGate(API_KEY).balance()
     self.assertTrue(balance > 0.0)
     self.assertEqual(type(balance), float)
コード例 #36
0
ファイル: test_cases.py プロジェクト: luis-wang/antigate
 def test_stats(self):
     stats = AntiGate(API_KEY).stats()
     self.assertTrue(len(stats) > 0)
     self.assertEqual(type(stats), list)
     self.assertEqual(type(stats[0]), OrderedDict)
コード例 #37
0
ファイル: send_capcha.py プロジェクト: muroslav2909/reserv
import time
from antigate import AntiGate            # AntiCaptcha

n = 1
while n<8:
    start = time.clock()
   # print AntiGate('888fe7041b163b35255dddafe49bfe6c', "/home/myroslav/reserv/reserv/visareserv/screenshot/res/%d.png" % n) # AntiCaptcha('API-KEY', 'captcha.jpg')
    print "n = %d" %n
    gate = AntiGate('888fe7041b163b35255dddafe49bfe6c')               # AntiCaptcha('API-KEY')
    captcha_id = gate.send("/home/myroslav/reserv/reserv/visareserv/screenshot/res/%d.png" % n)
    print gate.get(captcha_id)
    end = time.clock()
    n+=1
    interval = end - start
    print "interval =", interval
コード例 #38
0
 def test_balance(self):
     self.assertTrue(AntiGate(API_KEY).balance() > 0)
コード例 #39
0
class ChinaPostAirMail(tk.Tk):

    rowIndex = 0
    rows = []
    is_refreshing = False

    def _initDataBase(self):
        home = os.path.expanduser('~')
        self.db = shelve.open('%s/.air_mail.db' % home)

    def _createRow(self, data, j=0):
        row = []
        for j in range(len(data)):
            width = j == 2 and 50 or 20
            e = tk.Entry(self.fm, relief=tk.RIDGE, width=width, borderwidth=0)
            e.grid(row=self.rowIndex, column=j, sticky=tk.NSEW)
            e.insert(tk.END, data[j])
            row.append(e)
        tk.Button(
            self.fm, text='x', command=lambda: self.onDelete(data[1])).grid(
                row=self.rowIndex, column=(j + 1))
        self.rows.append(row)

        self.rowIndex += 1

    def _createTable(self):
        self.fm = tk.Frame(self, bg="white")
        self.fm.pack(side=tk.TOP, expand=tk.YES, fill=tk.NONE)
        keys = self.db.keys()
        keys.sort()
        for key in keys:
            if isinstance(self.db[key], list):
                self._createRow(self.db[key] + ['not sync'])

    def _addButtons(self):
        fm = tk.Frame(self, bg="white")
        fm.pack(side=tk.BOTTOM, expand=tk.YES, fill=tk.NONE)
        tk.Button(fm, text='Add', command=self.onAdd).grid(row=0, column=0)
        tk.Button(fm, text='Save', command=self.onSave).grid(row=0, column=1)
        tk.Button(fm, text='Refresh',
                  command=self.onRefresh).grid(row=0, column=2)
        tk.Button(fm, text='Settings',
                  command=self.onSettings).grid(row=0, column=3)
        tk.Button(fm, text='Clean', command=self.onClean).grid(row=0, column=4)
        tk.Button(fm, text='Close', command=self.onClose).grid(row=0, column=5)

    def _initStatusBar(self):
        label = tk.Label(text='Product')
        label.grid(row=0)

    def _addToDb(self, product, number):
        self._createRow([product, number, 'not sync'])
        self.db[number] = [product, number]
        self.db.sync()

    def _getText(self, element):
        return tools.text.normalize_space(tools.lxml_tools.get_node_text(
            element
        ))

    def __getCaptcha(self, image_file='/tmp/.air_mail.jpeg'):
        if hasattr(self, 'code'):
            return

        self.g.go('http://track-chinapost.com/startairmail.php')
        self.image = self.g.xpath('//img[@id="verifyimg"]').get('src')
        self.cookie = self.g.xpath('//input[@name="cookie"]').get('value')
        self.g.download(self.image, image_file)
        self.gate = AntiGate(self.db['api_key'], image_file)
        self.code = str(self.gate)

    def __getPage(self):
        self.g.setup(post={
            'code': self.code, 'num': self.number,
            'cookie': self.cookie, 'submit': ''
        })
        self.g.go('http://track-chinapost.com/track_chinapost.php')
        return self._getText(self.g.xpath('//div[@class="info"]/p'))

    def __getStatus(self):
        data = self.g.xpath_list('//table[@id="main_tab"]/tr')[-1]
        status = self._getText(data.xpath('td[3]')[0])
        date = self._getText(data.xpath('td[6]')[0])
        message = '%s / %s' % (status, date)
        if message == 'Status / Date':
            return 'no tracking info'
        return message

    def _getMailStatus(self):
        self.__getCaptcha()
        for i in range(3):
            info = self.__getPage()
            if 'verification code is wrong' in info:
                self.gate.abuse()
                del self.code
                self.__getCaptcha()
                continue
            return self.__getStatus()
        return 'error'

    def _setMessage(self, e, message):
        e.delete(0, tk.END)
        e.insert(tk.END, message)

    def _onRefresh(self):
        for row in self.rows:
            self._setMessage(row[STATUS], 'updating ...')
            self.number = row[KEY].get()
            try:
                status = self._getMailStatus()
            except:
                status = 'can not get info'
            self._setMessage(row[STATUS], status)
            time.sleep(5)
        del self.code
        self.is_refreshing = False

    def onRefresh(self):
        if self.is_refreshing:
            box.showinfo("Information", "Is running ...")
            return
        elif 'api_key' not in self.db.keys():
            box.showerror("Error", "API key is not set!")
            return
        else:
            self.is_refreshing = True
            thread.start_new_thread(self._onRefresh, ())

    def onAdd(self):
        TrackAddDialog(self, self._addToDb)

    def onClose(self):
        self.destroy()

    def onDelete(self, key):
        del self.db[key]
        self.db.sync()
        for row in self.rows:
            if row[KEY].get() == key:
                for e in row:
                    e.grid_forget()

    def onClean(self):
        for row in self.rows:
            for e in row:
                e.grid_forget()
        self.db.clear()
        self.db.sync()

    def onSave(self):
        for row in self.rows:
            key = row[KEY].get()
            if key in self.db.keys():
                self.db[key] = [row[NAME].get(), key]
        self.db.sync()

    def _saveSettings(self, api_key):
        self.db['api_key'] = api_key
        self.db.sync()

    def onSettings(self):
        SettingsDialog(self, self._saveSettings, self.db.get('api_key', ''))

    def _initGrab(self, cookie_file='/tmp/.airmail.cookie'):
        self.g = Grab()
        self.g.setup(
            hammer_mode=True, hammer_timeouts=((60, 70), (80, 90), (100, 110)),
            reuse_cookies=True, cookiefile=cookie_file
        )
        open(cookie_file, 'w').close()

    def main(self):
        self.title('ChinaPost / AirMail tracking')
        self._initGrab()
        self._initDataBase()
        self._addButtons()
        self._createTable()
        center(self)
        self.mainloop()

    def __del__(self):
        self.db.sync()
        self.db.close()
コード例 #40
0
    def solve(self, driver, limit_log=False):
        self.captcha_type = "recaptcha"  # could also be "text"
        done = False
        """
        Find captcha widget
        """
        found_widget = self.find_widget(driver, limit_log)
        if not found_widget:
            print "didnt find widget"
            return False
        """
        Find captcha popup
        """
        self.find_popup(driver, limit_log)
        """ STRESS TESTING
        test_input = raw_input("continue?")
        if not "y" in test_input:
            return False
        """

        if not limit_log:
            self.pmaster.log("doing challenge")
        done_challenge = False
        done_challenge_tries = 0

        while not done_challenge:
            print "inside while"
            if done_challenge_tries > self.max_try:
                return False
            try:
                """
                Get string challenge, table type and captcha image
                """
                self.challenge_str = driver.find_element_by_class_name(
                    "rc-imageselect-desc-no-canonical").text
                if not limit_log:
                    self.pmaster.log("challenge is '" + self.challenge_str +
                                     "'")
                """
                Gets table object and defines self.type
                """
                self.table = self.get_captcha_table(driver)
                #if self.type == "4x4":
                #if not limit_log:
                #self.pmaster.log("captcha is 4x4, exiting and will start again (if retry is > 1)")
                #return False
                """
                Gets full image to send to 2captcha
                """
                self.image_src = self.get_captcha_image(driver)

                done_challenge = True
            except:
                done_challenge_tries += 1

                # try if captcha is only text response
                try:
                    self.image_src = self.get_captcha_image(driver,
                                                            type="text")
                    self.captcha_type = "text"

                    self.captcha_text_answer = driver.find_element_by_id(
                        'default-response')
                    done_challenge = True
                except:
                    done_challenge_tries += 1
                    print "error: getting challenge image and string"
                    if not limit_log:
                        self.pmaster.log(
                            "error: getting challenge image and string")
                    done_challenge = False
        """
        Save image to /tmp/ folder
        """
        try:
            # save image
            resource = urllib.urlopen(self.image_src)
            self.dir_captcha_image = "tmp/captcha_" + str(
                random.randint(10000, 99999)) + ".jpg"
            output = open(self.dir_captcha_image, "wb")
            output.write(resource.read())
            output.close()

            if self.type == "4x4":
                outfile = self.dir_captcha_image
                size = (600, 600)
                try:
                    im = Image.open(outfile)
                    new_img = im.resize(size)
                    new_img.save(outfile, "JPEG")
                except IOError:
                    print "cannot create 600px img for '%s'" % outfile
                except Exception as e:
                    print "exception creating 600px img for 4x4 catpchas: " + str(
                        e)

        except Exception as e:
            print "Exception ocurred while saving image: " + str(e)
            return False
        """
        Captchas API's access
        """
        #if self.type != "4x4":
        if True:

            try:
                """
                2Captcha API
                """
                if self.captcha_api_service == "2captcha":

                    captcha2upload = CaptchaUpload(self.api_key)
                    self.service = captcha2upload
                    #self.log.warn("2captcha balance = "+captcha2upload.getbalance())

                    self.captcha_result = captcha2upload.solve(
                        self.dir_captcha_image,
                        text=self.challenge_str,
                        type=self.type)
                    print "data returned 2captcha = " + str(
                        self.captcha_result)
                    self.credit_used += 1

                    # couldnt solve
                    if self.captcha_result == 1:
                        self.pmaster.log(
                            "Captcha service couldn't find a solution")
                        self.report_bad_answer()
                        return False
                    else:
                        captcha_answer = True
                """
                Antigate API
                """
                if self.captcha_api_service == "antigate":

                    antigate = AntiGate(str(self.api_key))
                    self.service = antigate
                    #self.log.warn("antigate balance = "+str(antigate.balance()))

                    captcha_id = antigate.send(self.dir_captcha_image)
                    self.captcha_result = antigate.get(captcha_id)
                    print "data returned antigate = " + str(
                        self.captcha_result)
                    self.credit_used += 1

                    captcha_answer = True

                    self.clean_captcha_img()
                """
                ImageTyperz API
                """
                if self.captcha_api_service == "imagetyperz":

                    imagetyperz = ImageTyperz(self.api_user, self.api_pass)
                    self.service = imagetyperz
                    #self.log.warn("imagetyperz balance = "+imagetyperz.get_balance())

                    self.captcha_result = imagetyperz.solve(
                        self.dir_captcha_image)
                    print "data returned by imagetyperz = " + self.captcha_result
                    self.credit_used += 1

                    captcha_answer = True

                    self.clean_captcha_img()

            except AntiGateError:
                print "could not send captcha to Antigate"
                self.pmaster.log("could not send captcha to Antigate")

            except Exception as e:
                print "could not send captcha to" + self.captcha_api_service + "api = " + str(
                    e)
                self.pmaster.log("could not send captcha to " +
                                 self.captcha_api_service + " api = " + str(e))

        else:
            print "not trying 4x4 types...goodbye"
            if not limit_log:
                self.pmaster.log("4x4 captchas not supported")
            return False

        #if self.type != "4x4" and captcha_answer:
        if captcha_answer:
            if not limit_log:
                self.pmaster.log("answering captcha")
            ans = self.answer_captcha(driver, self.captcha_result)
            if ans:
                done = True

        return done
コード例 #41
0
ファイル: test_cases.py プロジェクト: luis-wang/antigate
 def test_base(self):
     self.assertEqual(str(AntiGate(API_KEY, IMAGE1)), '123')
コード例 #42
0
ファイル: test_cases.py プロジェクト: kostyll/antigate
 def test_load(self):
     load = AntiGate(API_KEY).load()
     self.assertTrue(len(load) > 0)
     self.assertEqual(type(load), OrderedDict)
     self.assertTrue(load.get('load') is not None)
コード例 #43
0
ファイル: common.py プロジェクト: andreyavramchikov/Email
def get_captcha(captcha_path):
    gate = AntiGate(settings.ANTIGATE_API_KEY, captcha_path)
    return gate.get(gate.captcha_id)
コード例 #44
0
 def test_captcha_config(self):
     config = {'min_len': '3', 'max_len': '4', 'numeric': '1'}
     ag = AntiGate(API_KEY, IMAGE1, send_config=config)
     self.assertEqual(str(ag), '123')
コード例 #45
0
ファイル: main.py プロジェクト: sstepashka/Parser
    def captcha(self, response):
        captcha_url = 'http://www.list-org.com/bot.php'

        cookie = response.info().getheader('Set-Cookie')

        opener = urllib2.build_opener(NoRedirection)
        opener.addheaders.append(('Cookie', cookie))
        urllib2.install_opener(opener)

        captcha_response = urllib2.urlopen(captcha_url)
        data = captcha_response.read()

        tree = html.fromstring(data)
        elements = tree.xpath('//div[@class="content"]/form/img/@src')

        # print data
        print 'CAPTCHA!!!!!!'
        # print response.info()

        if len(elements) > 0:
            image_url = elements[0]
            captcha_data = urllib2.urlopen(image_url).read()
			
            print 'image_url: ' + image_url

            with open('captcha.gif', "wb") as myfile:
                    myfile.write(captcha_data)
                    myfile.close()
            
            config = None

            if os.name == 'nt':
                config = {'is_russian': 1,}
            else:
                config = {'is_russian': '1',}

            
            gate = None
            while not gate:
                try:
                    gate = AntiGate(ANTIGATE_KEY, 'captcha.gif', send_config=config)
                    gate = gate.lower()
                except Exception, e:
                    print e

            file_path = 'captcha/' + str(gate) + '.gif'

            with open(file_path, "wb") as myfile:
                    myfile.write(captcha_data)

            values = {
                    'keystring' : str(gate),
                    'submit' : " Проверить! ",
                    }

            opener = urllib2.build_opener()
            opener.addheaders.append(('Cookie', cookie))
            urllib2.install_opener(opener)

            data = urllib.urlencode(values)
            req = urllib2.Request(captcha_url, data)
            req.get_method = lambda: 'POST'

            try:
                response = urllib2.urlopen(req)
                the_page = response.read()
                print the_page
            except urllib2.HTTPError, e:
                contents = e.read()
                print contents
コード例 #46
0
ファイル: test_cases.py プロジェクト: luis-wang/antigate
 def test_base_binary(self):
     fp = open(IMAGE1, 'rb')
     self.assertEqual(str(AntiGate(API_KEY, fp.read())), '123')
     fp.close()
コード例 #47
0
 def test_stats(self):
     self.assertTrue(len(AntiGate(API_KEY).stats()) > 0)
コード例 #48
0
ファイル: test_cases.py プロジェクト: luis-wang/antigate
 def test_base64(self):
     fp = open(IMAGE1, 'rb')
     self.assertEqual(str(AntiGate(API_KEY, b64encode(fp.read()))), '123')
     fp.close()
コード例 #49
0
 def test_base_binary(self):
     self.assertEqual(
         str(AntiGate(API_KEY, open(IMAGE1, 'rb').read(), binary=True)),
         '123')