def like(self, photo_id): captcha = False captcha_result = '' captcha_sid = '' while True: owner_id, item_id = photo_id.split('_') if captcha == False: url = self.getUrl.likes.add(type='photo', owner_id=owner_id, item_id=item_id) else: url = self.getUrl.likes.add(type='photo', owner_id=owner_id, item_id=item_id, captcha_sid=captcha_sid, captcha_key=captcha_result) self.requester(url, self.session) response = self.requester.request() for r in response: j = json.loads(r[0].text) try: if 'likes' in j['response']: with open('files/completed', 'a') as file: file.write(str(owner_id) + '\n') print('+', owner_id) return except Exception as e: print(e) print(r[0].text) if 'error' in j: if j['error']['error_code'] == 14: print("Решаем капчу") captcha = Captcha() captcha_result = captcha.solve(self.session, j['error']['captcha_img']) captcha_sid = j['error']['captcha_sid'] if captcha_result == 'error': self.interval = 2000 return else: captcha = True print(self.name, 'Captcha', captcha_result) if j['error']['error_code'] == 15: with open('files/completed', 'a') as file: file.write(str(owner_id) + '\n') print('+', owner_id) return if j['error']['error_code'] == 17: self.interval = 99999 return
def verify_code(self): timestemp = time.time() imgurl = 'http://api.chaxun.la/api/seccode/?0.{0}'.format(timestemp) if self.download(imgurl): captcha = Captcha() code_result = captcha.verification(filename='captcha.gif') self.verify = code_result.get('Result')
def __init__(self): self.POST_DATA = {} self.session = requests.Session() home_response = self.session.get(HOME_URL) dom = BeautifulSoup(home_response.content, "html.parser") inputs = dom.find_all('input') for input in inputs: if 'value' in input.attrs: self.POST_DATA[input.attrs['name']] = input.attrs['value'] else: self.POST_DATA[input.attrs['name']] = None self.captcha_url = dom.find(id="imgcap").attrs['src'] captcha_response = self.session.get(ROOT_URL + self.captcha_url) captcha_file = BytesIO() captcha_file.write(captcha_response.content) code = Captcha(captcha_file).crack() self.POST_DATA['txtCaptcha'] = code
def __init__(self): self.token = "Jh2044695" self.db = self.__gen_db("./middle.db") self.baseRange = 10 self.target = 5 self.sms = SmsHelper() self.captcha = Captcha()
async def verify_captcha(request): try: data = await request.json() is_verified = verify_user_captcha(data.get('widget_id'), data.get('input')) if not is_verified: captcha = Captcha() response = JSONResponse({ 'is_verified': is_verified, 'widget_id': captcha.widget_id, 'captcha_b64': captcha.b64_string }) else: response = JSONResponse({'is_verified': is_verified}) return response except Exception: response = Response('Error verifying captcha', status_code=500, media_type='text/plain') return response
def show_captcha(url): """ Muetra una imagen con el captcha y devuelve el texto escrito por el usuario :param url: :return: """ from captcha import Captcha skin = 'Estuary' if xbmc.getSkinDir() == 'skin.estuary' else 'Default' return Captcha("Captcha.xml", sysinfo.runtime_path, skin).start(url)
def login(url, parent=None, username=None, password=None): if (not password) or (not username): return None qDebug("in login") while True: session = _create_session() # qDebug("session") req = _get_login_page(session, url) # qDebug("page") captcha_id = re_search(r'img.src = \'captcha\?(.*)\'', req) # qDebug("captcha") if not captcha_id: qDebug('Captcha not found! Retrying...') sleep(3) continue captcha_id += get_timestamp() captcha_url = 'https://jaccount.sjtu.edu.cn/jaccount/captcha?' +\ captcha_id code = _bypass_captcha(parent, session, captcha_url) check = Captcha(parent) if not check.exec_(): session.close() return None code = check.captchaInput.text() qDebug(code) sid = re_search(r'sid" value="(.*?)"', req) returl = re_search(r'returl" value="(.*?)"', req) se = re_search(r'se" value="(.*?)"', req) client = re_search(r'client" value="(.*?)"', req) uuid = re_search(r'captcha\?uuid=(.*?)&t=', req) if not (sid and returl and se and uuid): qDebug('Params not found! Retrying...') sleep(3) continue res = _login(session, sid, returl, se, client, username, password, code, uuid) if res == 2: parent.LogInfo.emit('[MSG]Wrong captcha! Try again!\n') qDebug('Wrong captcha! Try again!') continue elif res == 1: parent.LogInfo.emit( '[MSG]Wrong username or password! Try again!\n' ) qDebug('Wrong username or password! Try again!') break elif res == 3: parent.LogInfo.emit( '[MSG]Opps! You are banned for 30s...Waiting...\n' ) qDebug('Opps! You are banned for 30s...Waiting...') sleep(30) continue else: return session
def captcha(): c = Captcha() info = c.create_captcha() image = os.path.join(app.config['BASE_DIR'],'static/captcha/') + info['image_name'] # 读取验证码 with open(image,'rb') as f: image = f.read() # 获取验证码具体字母和数字 session['captcha'] = info['captcha'] return Response(image,mimetype='jpeg')
def captcha(): from captcha import Captcha c = Captcha() info = c.create_captcha() image = os.path.join(os.path.dirname(__file__), "static/captcha") + "/" + info["image_name"] with open(image, 'rb') as f: image = f.read() session['captcha'] = info["captcha"] # print(session['captcha']) return Response(image, mimetype="jpeg")
def captcha(): from captcha import Captcha c = Captcha() info = c.create_captcha() image = os.path.join(os.path.dirname(__file__), 'static/captcha') + '/' + info['image_name'] with open(image, 'rb') as f: image = f.read() # 进行会话session中值的保存 session['captcha'] = info['captcha'] # print(session['captcha']) return Response(image, mimetype='jpeg')
def test_post_verify_captcha(): client = TestClient(app) captcha = Captcha() response = client.post('/verify-captcha/', headers={'Content-Type': 'application/json'}, json={ 'widget_id': captcha.widget_id, 'input': ''.join(captcha.characters) }) assert response.status_code == 200
async def new_member_handler(message: types.Message): num = str(random.choices(range(1000, 9999))[0]) filename = f'{uuid.uuid4()}.png' Captcha(filename, num).create() with open(filename, 'rb') as captcha: await bot.send_photo(message.chat.id, captcha, caption=Template.CAPTCHA.format(f'@{message["from"].username}')) os.remove(filename) redis_key = f'{message.chat.id}_{message["from"].id}' redis_data = json.dumps({ "answer": num, "kick_time": (datetime.datetime.utcnow() + datetime.timedelta(minutes=KICK_TIME_MINUTE)).strftime(FORMAT_TIME), "username": message['from'].username }) await redis_dispatcher.append_quque_user(redis_key, redis_data)
async def get_captcha(request): try: captcha = Captcha() data = { 'widget_id': captcha.widget_id, 'captcha_b64': captcha.b64_string } return JSONResponse(data) except Exception: response = Response('Error generating captcha', status_code=500, media_type='text/plain') return response
def captcha_page(session, referer, pname): """Takes a Session and long_id and retrieves a captcha.png file to be processed. Returning the cracked code for its caller.""" captcha_url = 'http://buscatextual.cnpq.br/buscatextual/servlet/captcha?'\ 'metodo=getImagemCaptcha' headers = {} headers['Accept'] = 'image/png,image/*;q=0.8,*/*;q=0.5' headers['Accept-Encoding'] = 'gzip, deflate' headers['Accept-Language'] = 'en-US,en;q=0.5' headers['Connection'] = 'keep-alive' headers['DNT'] = '1' headers['Host'] = 'buscatextual.cnpq.br' headers['Referer'] = referer img_name = 'captcha_' + current_process().name + '.png' while True: try: logging.info('%s-captcha_page: Getting captcha page.', pname) headers['User-Agent'] = USER_AGENT.random req = session.get(captcha_url, headers=headers) except requests.exceptions.Timeout as terror: logging.info('%s-captcha_page: Timeout: %s\nTrying again...', pname, terror) continue except requests.exceptions.ConnectionError as cerror: logging.info( '%s-captcha_page: Connection Error: %s\nTrying ' 'again...', pname, cerror) continue except requests.exceptions.RequestException as rerror: logging.info( '%s-captcha_page: Request Error: %s\nTrying ' 'again...', pname, rerror) continue if req.status_code != 200: continue try: open(img_name, 'wb').write(req.content) code = Captcha(img_name).get_text().upper() if len(code) == 4: logging.info('%s-captcha_page: Right captcha length: %s', pname, code) return code except Exception, ioerror: logging.info('%s-captcha_page: %s', pname, ioerror) continue
def gen_helper(arg): global font_path global bg_path global o_dir global captcha_size char, char_idx = arg rotate = random.randint(-15, 15) font_size = random.randint(700, 800) bg_offset = (random.randint(0, 400), random.randint(0, 1000)) c = Captcha(font_path=font_path, bg_path=bg_path, rotate=rotate, font_size=font_size, bg_offset=bg_offset) o_fname = os.path.join( o_dir, "{0}_{1}-{2}".format(char, str(bg_offset), char_idx)) c.generate(char, o_fname=o_fname, captcha_size=captcha_size)
def __init__(self, card_id, user_list, callback, i): threading.Thread.__init__(self) self.url_get = 'http://hao.17173.com/gift-captcha.html?refresh=1&gift_id=%d&_=%d' self.url_img = 'http://hao.17173.com%s' self.url_submit = 'http://hao.17173.com/gift-qiang-%d.html' self.card_id = card_id self.user_list = user_list self.callback = callback self.captcha = Captcha() self.i = i webCookie = http.cookiejar.CookieJar() cookie_handler = urllib.request.HTTPCookieProcessor(webCookie) self.openner = urllib.request.build_opener(cookie_handler) #proxy_handler = urllib.request.ProxyHandler({'http': 'child-prc.intel.com:913'}) #self.openner = urllib.request.build_opener(cookie_handler, proxy_handler) self.thread_stop = False
def test_2_should_be_two(self): captcha = Captcha(self.secondPattern, self.dummyLeftOperand, self.dummyOperator, 2) self.assertEqual('two', captcha.rightOperand.toString())
def test_1_should_be_one(self): captcha = Captcha(self.secondPattern, self.dummyLeftOperand, self.dummyOperator, 1) self.assertEqual('one', captcha.rightOperand.toString())
def test_4_should_be_three(self): captcha = Captcha(self.secondPattern, 4, self.dummyOperator, self.dummyRightOperand) self.assertEqual('four', captcha.leftOperand.toString())
def test_2_should_be_2(self): captcha = Captcha(self.firstPattern, 2, self.dummyOperator, self.dummyRightOperand) self.assertEqual('2', captcha.leftOperand.toString())
def test_get_json(self): captcha = Captcha(1, 1, 1, 1) output = Output(captcha) self.assertEqual('{"operator": "+", "right": "one", "left": "1"}', output.json())
from captcha import Captcha from recognizer import Recognizer captcha = Captcha() captcha.split_all_captchas() recognizer = Recognizer() recognizer.load_captcha_folder('./letter_imgs') recognizer.train_model() recognizer.predict_model('476802131.png') recognizer.run_in_test_folder('./captcha_test_imgs')
def test_3_should_be_minus(self): captcha = Captcha(self.dummyPattern, self.dummyLeftOperand, 3, self.dummyRightOperand) self.assertEqual('-', captcha.operator.toString())
def test_1_should_be_plus(self): captcha = Captcha(self.dummyPattern, self.dummyLeftOperand, 1, self.dummyRightOperand) self.assertEqual('+', captcha.operator.toString())
def crack_captcha(self): flag = True count = 1 while count <= self.crack_times: # noinspection PyBroadException try: # 等待验证码提示框出现 WebDriverWait(self.driver, 10, 0.5).until( EC.presence_of_element_located( (By.ID, 'tcaptcha_transform'))) # 切换iframe self.driver.switch_to.frame( self.driver.find_element_by_css_selector( 'iframe#tcaptcha_iframe')) # 生成验证码操作类实例 captcha = Captcha() # 定位验证码图片并下载到本地(背景大图, 滑块小图) background = self.driver.find_element_by_id('slideBg') if not self.wait_image_loaded(background): raise CrackCaptchaException("加载背景大图失败!") # 获取src属性值 bg_url = background.get_attribute('src') if not captcha.download_image(bg_url, 'bg_block.png'): raise CrackCaptchaException("下载背景大图[%s]失败!" % bg_url) slide_block = self.driver.find_element_by_id('slideBlock') sb_url = slide_block.get_attribute('src') if not captcha.download_image(sb_url, 'sb_block.png'): raise CrackCaptchaException("下载滑块小图[%s]失败!" % sb_url) # 获取页面图片大小及位置 bg_width = background.size['width'] bg_loc_x = background.location['x'] sb_loc_x = slide_block.location['x'] # 获取原图大小 actual_width, actual_height = captcha.get_size('bg_block.png') # 获取滑块原图在背景原图中的位置, 即(行, 列)坐标 # 行坐标即距离top的长度, 列坐标即距离left的长度 position = captcha.get_position('bg_block.png', 'sb_block.png', False) # 按比例换算页面滑块图片在页面背景图片中的位置 slide_position_x = int(bg_width / actual_width * position[1]) # 页面滑块图片活动距离 slide_distance = slide_position_x - (sb_loc_x - bg_loc_x) track_list = captcha.get_track(slide_distance) # 定位滑块 drag_button = self.driver.find_element_by_id( 'tcaptcha_drag_button') # 滑动滑块 self.drag_and_drop(drag_button, track_list) # 判断是否成功 if self.is_element_dismiss((By.ID, 'tcWrap'), 2): flag = True LOGGER.info("第%d次尝试破解滑动验证码: 成功!" % count) break else: flag = False raise CrackCaptchaException("第%d次尝试破解滑动验证码: 失败!" % count) except CrackCaptchaException as cce: LOGGER.error(str(cce)) count += 1 # 点击刷新按钮, 重新加载验证码 self.wait_clickable((By.ID, 'reload')) # self.wait_click(self.driver.find_element_by_id('reload')) time.sleep(1) # 切换回默认dom树 self.driver.switch_to.default_content() continue except Exception as e: raise e return flag
from selenium.webdriver.common.action_chains import ActionChains from win10toast import ToastNotifier # python -m pip install win10toast # Browser config chromedriver_path = '.\\chromedriver.exe' # <-- Change to your Chrome WebDriver path, replace "\" with "\\". opts = Options() opts.binary_location = 'C:\\Program Files\\BraveSoftware\\Brave-Browser\\Application\\brave.exe' # <-- Change to your Chromium browser path, replace "\" with "\\". opts.add_experimental_option('excludeSwitches', ['enable-automation']) opts.add_experimental_option('useAutomationExtension', False) # opts.add_argument('--proxy-server=%s' % 'YourProxy') # <-- Remove comment this line then replace 'YourProxy' by proxy string, such as 18.222.190.66:81. # Captcha config autoCaptcha = True # <-- Change to True if you want to use 2captcha to solve the captcha. if autoCaptcha: # Replace by your 2Captcha API Key --> rc = Captcha('Your2CaptchaAPIKey') # <-- Replace by your 2Captcha API Key # App config app = 'Alien Worlds' loginPath = 'https://all-access.wax.io' gamePath = 'https://play.alienworlds.io' waxio_cookies = [ { 'name': 'token_id', # Replace by your token id --> 'value': 'YourTokenId', # <-- Replace by your token id 'domain': 'all-access.wax.io', 'path': '/', },
def test_2_should_be_multiply(self): captcha = Captcha(self.dummyPattern, self.dummyLeftOperand, 2, self.dummyRightOperand) self.assertEqual('*', captcha.operator.toString())
def setUp(self): self.c = Captcha()
def __init__(self, domain): super(Sitedossier, self).__init__() self.domain = domain self.captcha = Captcha() self.subset = []
def fill_code(self): code_img = self.webdriver.find_element(*self.code_img) if code_img.is_displayed(): code = Captcha().img(self.webdriver, code_img).resolve() self.fill_elements({self.code_element: code})