def captcha_handler(captcha): if ANTICAPTCHA_KEY == '': solution = input("Решите капчу ({0}): ".format(captcha.get_url())) return captcha.try_again(solution) key = ImageToTextTask.ImageToTextTask( anticaptcha_key=ANTICAPTCHA_KEY, save_format='const').captcha_handler(captcha_link=captcha.get_url()) return captcha.try_again(key['solution']['text'])
def captcha_handler(captcha): if info['captcha_key'] is None: class show_image(Thread): def __init__(self, image, title): Thread.__init__(self) self.image = image self.title = title def run(self): img = cv2.imread(self.image) cv2.imshow(self.title, img) cv2.waitKey(0) resource = urllib.request.urlopen(captcha.get_url()) out = open('captcha.jpg', 'wb') out.write(resource.read()) out.close() show = show_image('captcha.jpg', 'captcha!') show.start() key = input( 'Введите каптчу, которая появилась в отдельном окне: ').strip() print('Каптча решена! Закройте окно с каптчей.') return captcha.try_again(key) try: print('Каптча! Пробуем решить каптчу...') key = ImageToTextTask.ImageToTextTask( anticaptcha_key=(info['captcha_key']), save_format='const').captcha_handler( captcha_link=(captcha.get_url()))['solution']['text'] print('Каптча решена!') return captcha.try_again(key) except KeyError: print('Не удалось решить каптчу!')
def test_get_result_payload(self): customcaptcha = ImageToTextTask.ImageToTextTask( anticaptcha_key=self.anticaptcha_key_fail) # check response type assert isinstance(customcaptcha, ImageToTextTask.ImageToTextTask) with requests_mock.Mocker() as req_mock: req_mock.register_uri("GET", self.image_url, json=self.VALID_RESPONSE_JSON) req_mock.register_uri("POST", config.create_task_url, json=self.VALID_RESPONSE_JSON) req_mock.register_uri("POST", config.get_result_url, json=self.VALID_RESPONSE_RESULT_JSON) customcaptcha.captcha_handler(captcha_link=self.image_url) history = req_mock.request_history assert len(history) == 3 request_payload = history[2].json() # check all dict keys assert ["clientKey", "taskId"] == list(request_payload.keys()) assert request_payload["taskId"] == self.VALID_RESPONSE_JSON["taskId"]
def test_fail_imagecaptcha_temp(self): imagecaptcha = ImageToTextTask.ImageToTextTask( anticaptcha_key=self.anticaptcha_key_fail, save_format=ImageToTextTask.SAVE_FORMATS[1]) response = imagecaptcha.captcha_handler(captcha_link=self.image_url) assert 1 == response["errorId"]
def test_fail_imagecaptcha_const_context(self): with ImageToTextTask.ImageToTextTask( anticaptcha_key=self.anticaptcha_key_fail, save_format=ImageToTextTask.SAVE_FORMATS[0] ) as imagecaptcha: response = imagecaptcha.captcha_handler(captcha_link=self.image_url) assert 1 == response["errorId"]
def captcha_handler(captcha): ''' Отлавливание каптчи :param captcha: Объект капчи :return: Новая_попытка_отправить_сообщение_с_введенной_капчей ''' key = ImageToTextTask.ImageToTextTask(anticaptcha_key=info.captcha, save_format='const') \ .captcha_handler(captcha_link=captcha.get_url()) # Пробуем снова отправить запрос с капчей return captcha.try_again(key['solution']['text'])
def test_response_imagecaptcha(self): imagecaptcha = ImageToTextTask.ImageToTextTask(anticaptcha_key=self.anticaptcha_key_fail) # check response type assert isinstance(imagecaptcha, ImageToTextTask.ImageToTextTask) response = imagecaptcha.captcha_handler(captcha_link=self.image_url) # check response type assert isinstance(response, dict) # check all dict keys assert ["errorId", "errorCode", "errorDescription"] == list(response.keys())
def captcha_handler(captcha): r = requests.get(captcha.get_url()) encoded = base64.b64encode(r.content).decode() dt = ImageToTextTask.ImageToTextTask( anticaptcha_key=global_config.ANTIGATE_KEY).captcha_handler( captcha_base64=encoded) user_answer = dt['solution']['text'] return captcha.try_again(user_answer)
def login_captca(num, psw, code, path): driver = webdriver.Chrome(path) driver.get("https://obs.iyte.edu.tr/oibs/ogrenci/login.aspx") assert "No results found." not in driver.page_source ANTICAPTCHA_KEY = str(code) image_link = 'https://obs.iyte.edu.tr/oibs/ogrenci/login.aspx' user_answer = ImageToTextTask.ImageToTextTask(anticaptcha_key = ANTICAPTCHA_KEY).\ captcha_handler(captcha_link=image_link) element = driver.find_element_by_id("imgCaptchaImg").screenshot_as_png im = Image.open(BytesIO(element)) im.save('./image.png') image_path = '.\/image.png' user_answer = ImageToTextTask.ImageToTextTask( anticaptcha_key=ANTICAPTCHA_KEY).captcha_handler( captcha_file=image_path) solution = user_answer["solution"]["text"] print(user_answer) print(solution) numara = num password = psw time.sleep(10) numara_input = driver.find_element_by_name("txtParamT01") numara_input.send_keys(numara) pass_input = driver.find_element_by_name("txtParamT02") pass_input.send_keys(password) inputelem = driver.find_element_by_name("txtSecCode") inputelem.send_keys(solution) submit = driver.find_element_by_name("btnLogin") submit.click() return driver
def captcha_handler(captcha): ''' Отлавливание каптчи :param captcha: Объект капчи :return: Новая_попытка_отправить_сообщение_с_введенно_капчей ''' key = ImageToTextTask.ImageToTextTask(anticaptcha_key=antiCaptchaKey, save_format='const') \ .captcha_handler(captcha_link=captcha.get_url()) logs.write('IMPORTANT: Entered captcha. Key: ' + str(key)) # Пробуем снова отправить запрос с капчей return captcha.try_again(key['solution']['text'])
def ImageCaptcha(image_link): ANTICAPTCHA_KEY = "cfff02538f8b393ab3df35257154f982" try: user_answer = ImageToTextTask.ImageToTextTask( anticaptcha_key=ANTICAPTCHA_KEY).captcha_handler( captcha_file=image_link) if user_answer['errorId'] == 0: return user_answer['solution']['text'] elif user_answer['errorId'] == 1: return user_answer['errorBody'] except Exception as erro: return erro
def SolveCapcha(): try: print("method is called") image_link = url + driver.find_element_by_xpath( '//*[@id="container"]/div/div[2]/div/div[1]/div[4]/div/div/div[1]/div/label[5]/div[2]/div/div/div[3]/form/div/div[1]/img[1]' ).get_attribute('src') print(image_link) ANTICAPTCHA_KEY = "masked" user_answer = ImageToTextTask.ImageToTextTask(anticaptcha_key=ANTICAPTCHA_KEY).\ captcha_handler(captcha_link=image_link) print(user_answer['solution']['text']) return user_answer['solution']['text'] except Exception as e: print(e)
def captcha_handler(captcha): """ При возникновении капчи вызывается эта функция и ей передается объект капчи. Через метод get_url можно получить ссылку на изображение. Через метод try_again можно попытаться отправить запрос с кодом капчи """ """ Для решении капчи используется сервис https://anti-captcha.com/ от вас требуется только ввести token пользователя 1000 рекапч = ~70 рублей """ token = '' key = ImageToTextTask.ImageToTextTask( anticaptcha_key=token, save_format='const').captcha_handler(captcha_link=captcha.get_url()) print(captcha.get_url()) # Пробуем снова отправить запрос с капчей return captcha.try_again(key['solution']['text'])
def Captcha_Handling(real_url, headers, cookies, ANTICAPTCHA_KEY): url_image = 'http://www.zone-h.org/captcha.py' response_image = requests.get(url_image, headers=headers, cookies=cookies, stream=True) with open('captcha.png', 'wb') as out_file: shutil.copyfileobj(response_image.raw, out_file) user_answer_local = ImageToTextTask.ImageToTextTask(anticaptcha_key = ANTICAPTCHA_KEY).\ captcha_handler(captcha_file = 'captcha.png') captcha_data = user_answer_local['solution']['text'] data = {'defacer':'', 'domain':'.vn', 'filter_date_select': '', 'filter_date_y':'', 'filter_date_m':'',\ 'filter_date_d':'', 'filter': 1, 'fulltext': 'on', 'archivecaptcha': captcha_data} #'published': 0, response = requests.post(real_url, data=data, headers=headers, cookies=cookies) return response
def anti_captcha(self, my_id, my_pw): print('안티캡챠 실행') # 캡챠 이미지 원소 elem_captcha_img = self.find_element('//*[@id="captchaimg"]') # 캡챠 이미지 주소 captcha_img_url = elem_captcha_img.get_attribute('src') try: # 캡챠 정답 captcha_answer = ImageToTextTask.ImageToTextTask(anticaptcha_key=self.anticaptcha_key, save_format='const') \ .captcha_handler(captcha_link=captcha_img_url) except IdGetError: print('안티캡챠 밸런스 모두 사용함! 결제해야 함!') exit() if not 'solution' in captcha_answer: print('로그인 재시도') self.naver_login(my_id, my_pw) return # 캡챠 정답 captcha_text = captcha_answer['solution']['text'] # 비밀번호 쓰기 elem_pw = self.find_element('//*[@id="pw"]') elem_pw.send_keys(my_pw) # 캡챠 정답 쓰기 elem_captcha_fld = self.find_element('//*[@id="chptcha"]') elem_captcha_fld.send_keys(captcha_text) elem_pw.submit() # 네이버 메인 elem_main = self.find_element('//*[@id="PM_ID_ct"]') if elem_main is None: print('로그인 재시도') self.naver_login(my_id, my_pw)
def captcha_handler(captcha): """ При возникновении капчи вызывается эта функция и ей передается объект капчи. Через метод get_url можно получить ссылку на изображение. Через метод try_again можно попытаться отправить запрос с кодом капчи """ print("Captcha url: {0}".format(captcha.get_url())) anti_captcha_key = 'ANTI_CAPTCHA_KEY' code = ImageToTextTask.ImageToTextTask( anticaptcha_key=anti_captcha_key).captcha_handler( captcha_base64=base64.b64encode( requests.get(captcha.get_url(), headers=headers).content).decode("utf-8")) print(code) if 'solution' in code and 'text' in code['solution']: key = code['solution']['text'] else: key = input("Enter captcha code {0}: ".format( captcha.get_url())).strip() print(f"key={key}") # Пробуем снова отправить запрос с капчей return captcha.try_again(key)
def test_fail_imagecaptcha_value(self): with pytest.raises(ValueError): assert ImageToTextTask.ImageToTextTask( anticaptcha_key=self.anticaptcha_key_fail, save_format=self.WRONG_SAVE_FORMAT)
def captcha_handler(captcha): key = ImageToTextTask.ImageToTextTask(anticaptcha_key=info.captcha, save_format='const') \ .captcha_handler(captcha_link=captcha.get_url()) return captcha.try_again(key['solution']['text'])
def captcha_handler(captcha): key = ImageToTextTask.ImageToTextTask(anticaptcha_key=anticaptcha_key, save_format='const') \ .captcha_handler(captcha_link=captcha.get_url()) # Пробуем снова отправить запрос с капчей return captcha.try_again(key['solution']['text'])
# api_key = 'f89f8380c361f21a88986b608ea7334b' # "D:\Projetos\PycharmProjects\virtualenv\SituacaoCadastral\Codigo\captcha_ms.jpeg" # https://anti-captcha.com/mainpage from python3_anticaptcha import ImageToTextTask ANTICAPTCHA_KEY = "" image_link = "gerarCaptcha.png" user_answer = ImageToTextTask.ImageToTextTask(anticaptcha_key = ANTICAPTCHA_KEY).\ captcha_handler(captcha_file=image_link) print(user_answer)
from python3_anticaptcha import ImageToTextTask ANTICAPTCHA_KEY = "" # Пример который показывает работу антикапчи при решении капчи-изображением и сохранением её в качестве обычного файла в # папку result = ImageToTextTask.ImageToTextTask(anticaptcha_key = ANTICAPTCHA_KEY, save_format = 'const')\ .captcha_handler('http://85.255.8.26/static/image/common_image_example/800070.png') print(result) """ Данная библиотека реализует два различных метода для сохранения изображений(для последующей их передачи сервису): 1. В качестве временного файла, параметр задаётся по умолчанию, но для того что бы его объявить явно нужно передать save_format = 'temp' . 2. В качестве обычного файла, для этого нужно передать: save_format = 'const' . """ # Пример который показывает работу антикапчи при решении капчи-изображением и сохранением её в качестве ВРЕМЕННОГО файла result = ImageToTextTask.ImageToTextTask(anticaptcha_key = ANTICAPTCHA_KEY)\ .captcha_handler('http://85.255.8.26/static/image/common_image_example/800070.png') print(result)
def aws(firstName,emailId,number,proc,return_dict): # global driver global cnumber global expMonth global expYear global cvc addressDict = generate_address() while True: try: options = Options() # options.headless = True driver = webdriver.Firefox(options=options) # chromeOptions = webdriver.ChromeOptions() # chromeOptions.add_argument('--incognito') # driver = webdriver.Chrome(executable_path='chromedriver.exe',chrome_options=chromeOptions) driver.get('https://portal.aws.amazon.com/billing/signup#/start') email_address = WebDriverWait(driver,10).until( EC.presence_of_element_located((By.ID,'ccEmail')) ) email_address.send_keys(emailId) pswd = driver.find_element_by_id('ccPassword') pswd.send_keys(RESET_PSWD) repswd = driver.find_element_by_id('ccRePassword') repswd.send_keys(RESET_PSWD) awsname = driver.find_element_by_id('ccUserName') awsname.send_keys(firstName) continue_btn = WebDriverWait(driver,10).until( EC.element_to_be_clickable((By.XPATH,'/html/body/div[1]/div/div[1]/div[2]/div[1]/div/div[1]/div[2]/div/div[5]/button/span/input')) ) continue_btn.click() personal = WebDriverWait(driver,10).until( EC.element_to_be_clickable((By.ID,'personal-account')) ) personal.click() phoneNumber = driver.find_element_by_id('phone-number') phoneNumber.send_keys(number) country = WebDriverWait(driver,10).until( EC.element_to_be_clickable('/html/body/div[1]/div/div[1]/div[2]/div/div[2]/div[2]/div[1]/div/div[4]/select') ) # country = driver.find_element_by_xpath() country.click() country_choose = WebDriverWait(driver,10).until( EC.element_to_be_clickable((By.XPATH,'/html/body/div[1]/div/div[1]/div[2]/div/div[2]/div[2]/div[1]/div/div[4]/select/option[102]')) ) # country_choose = driver.find_element_by_xpat('') country_choose.click() adress = driver.find_element_by_id('street-address-1') adress.send_keys(addressDict['street']) city = driver.find_element_by_id('city') city.send_keys(addressDict['city']) state = driver.find_element_by_id('state') state.send_keys(addressDict['state']) postal_code = driver.find_element_by_id('postal-code') postal_code.send_keys(addressDict['pincode']) agree = WebDriverWait(driver,10).until( EC.element_to_be_clickable((By.XPATH,'/html/body/div[1]/div/div[1]/div[2]/div/div[2]/div[2]/agreement/div/div[2]/input')) ) # agree = driver.find_element_by_xpath('/html/body/div[1]/div/div[1]/div[2]/div/div[2]/div[2]/agreement/div/div[2]/input') agree.click() account_create = WebDriverWait(driver,10).until( EC.element_to_be_clickable((By.XPATH,'/html/body/div[1]/div/div[1]/div[2]/div/div[2]/div[2]/div[3]/button/span/input')) ) # account_create = driver.find_element_by_xpath('/html/body/div[1]/div/div[1]/div[2]/div/div[2]/div[2]/div[3]/button/span/input') account_create.click() proc.join() ccnumber = WebDriverWait(driver,10).until( EC.presence_of_element_located((By.ID,'addCreditCardNumber')) ) ccnumber.send_keys(return_dict['cnumber']) WebDriverWait(driver,10).until( EC.element_to_be_clickable((By.ID,'expirationMonth')) ) select = Select(driver.find_element_by_id('expirationMonth')) select.select_by_value(str(int(return_dict['expMonth']) - 1)) select_year = Select(driver.find_element_by_xpath('/html/body/div[1]/div/div[1]/div[2]/div/div[2]/div[2]/div/div[1]/sup-credit-card-input/div/div[2]/div/select[2]')) select_year.select_by_visible_text('20' +str(expYear)) cvc_number = driver.find_element_by_id('cvc') cvc_number.send_keys(return_dict['cvc']) acntName = driver.find_element_by_id('accountHolderName') acntName.send_keys(firstName) pan_no = driver.find_element_by_xpath('/html/body/div[1]/div/div[1]/div[2]/div/div[2]/div[2]/div/span/span/div/div/label[2]/input') pan_no.click() verify = driver.find_element_by_xpath('/html/body/div[1]/div/div[1]/div[2]/div/div[2]/div[2]/div/div[3]/button/span/span[1]') choice = input("Verify(y/n") if choice == "n": break verify.click() otpTransact = WebDriverWait(driver,60).until( EC.presence_of_element_located((By.ID,'txtAutoOtp')) ) otpt = input("Enter otp for transaction:") otpTransact.send_keys(otpt) time.sleep(2) WebDriverWait(driver,10).until( EC.element_to_be_clickable((By.XPATH,'/html/body/form/div/div/div/div/div/div[3]/div[15]/div/div[1]/input')) ).click() textSelect = WebDriverWait(driver,60).until( EC.element_to_be_clickable((By.XPATH,'/html/body/div[1]/div/div[1]/div[2]/div/div[1]/div[2]/div[2]/div[1]/div[1]/div/label[1]/input')) ) textSelect.click() WebDriverWait(driver,20).until( EC.presence_of_element_located((By.ID,'phoneNumber')) ).send_keys(phone_number) # driver.find_element_by_id('').send_keys(phone_number) # p2.join() imgLink = WebDriverWait(driver,10).until( EC.presence_of_element_located((By.ID,'imageCaptcha')) ).get_attribute("ng-src") print("Solving Captcha") user_answer = ImageToTextTask.ImageToTextTask(anticaptcha_key=ANTICAPTCHA_KEY). \ captcha_handler(captcha_link=imgLink) print(user_answer) if int(user_answer['errorId']) == 0: captchaAnswer = str(user_answer['solution']['text']) else: print("Captcha Not Solved") WebDriverWait(driver,10).until( EC.presence_of_element_located((By.ID,'guess')) ).send_keys(captchaAnswer) WebDriverWait(driver,10).until( EC.element_to_be_clickable((By.XPATH,'/html/body/div[1]/div/div[1]/div[2]/div/div[1]/div[2]/div[2]/div[2]/button/div[1]/span/input')) ).click() while True: final_otp = input("Please enter otp: ") if final_otp == "resend": # WebDriverWait(driver,10).until( # EC.element_to_be_clickable((By.XPATH,'/html/body/div[1]/div/div[1]/div[2]/div/div[2]/div[1]/div/div[3]/span/span/a')) # ).click() script = input("Please enter runtime execution script") runtime_script(driver,script) time.sleep(2) while True: try: a = driver.switch_to.alert() a.accept() break except: print("Alert not found") time.sleep(1) textSelect = WebDriverWait(driver, 60).until( EC.element_to_be_clickable((By.XPATH, '/html/body/div[1]/div/div[1]/div[2]/div/div[1]/div[2]/div[2]/div[1]/div[1]/div/label[1]/input')) ) textSelect.click() WebDriverWait(driver,10).until( EC.element_to_be_clickable((By.ID,'countryCode')) ) select = Select(driver.find_element_by_id('countryCode')) select.select_by_value("101") WebDriverWait(driver, 20).until( EC.presence_of_element_located((By.ID, 'phoneNumber')) ).send_keys(phone_number) imgLink = WebDriverWait(driver, 10).until( EC.presence_of_element_located((By.ID, 'imageCaptcha')) ).get_attribute("ng-src") print("Solving Captcha") user_answer = ImageToTextTask.ImageToTextTask(anticaptcha_key=ANTICAPTCHA_KEY). \ captcha_handler(captcha_link=imgLink) print(user_answer) WebDriverWait(driver, 10).until( EC.presence_of_element_located((By.ID, 'guess')) ).send_keys(user_answer) WebDriverWait(driver, 10).until( EC.element_to_be_clickable((By.XPATH, '/html/body/div[1]/div/div[1]/div[2]/div/div[1]/div[2]/div[2]/div[2]/button/div[1]/span/input')) ).click() else: WebDriverWait(driver,10).until( EC.presence_of_element_located((By.XPATH,'/html/body/div[1]/div/div[1]/div[2]/div/div[2]/div[1]/div/div[3]/div[1]/input')) ).send_keys(final_otp) time.sleep(2) driver.execute_script("document.getElementsByClassName('sms-verify-btn')[0].children[0].click()") time.sleep(1) driver.execute_script("document.getElementsByClassName('a-button-text')[3].click()") time.sleep(1) driver.execute_script("document.getElementsByClassName('a-button-input')[0].click()") WebDriverWait(driver,10).until( EC.element_to_be_clickable((By.XPATH,'/html/body/div[1]/main/section/div/div[2]/div/div/div/div/form/fieldset/div/div[3]/div/div/div/div/span')) ) driver.execute_script("document.querySelector('#aws-element-e325bdc6-4088-4113-bde9-ad2c6411b8ce > div:nth-child(2) > div:nth-child(2) > ul:nth-child(1) > li:nth-child(8)')") driver.execute_script("document.querySelector('#aws-element-3f5165f1-815e-4d9e-aff3-dced5594974f > div:nth-child(2) > div:nth-child(2) > ul:nth-child(1) > li:nth-child(8)').click()") WebDriverWait(driver,10).until( EC.element_to_be_clickable((By.XPATH,'/html/body/div[1]/main/section/div/div[2]/div/div/div/div/form/fieldset/div/div[6]/div/div/div/div/button')) ).click() WebDriverWait(driver,10).until( EC.presence_of_element_located((By.XPATH,'/html/body/div[1]/main/section/div/div[2]/div/div/div/div/div/div/div/div/div/div/h1/a')) ) WebDriverWait(driver,10).until( EC.element_to_be_clickable((By.XPATH,'//*[@id="aws-element-button-0f3b8a22-a00a-4b4b-8be8-274a07524883"]')) ).click() print("Account Created") if input("Do you want to exit: ") == "y": break break except Exception as e: print(f"Exception occured {e}") createChoice = input("Want to create another driver(y/n") if createChoice == "y": while True: newNumber = random.randint(1000,9999) if newNumber != int(email_id.split(firstName + firstName[0].lower())[1].split("@")[0]): emailId = f"{firstName}{newNumber}@ruru.be" # p2.join() # p2 = Process(target=email_create,args=(emailId,)) # p2.start() break else: continue
from python3_anticaptcha import ImageToTextTask from python3_anticaptcha import errors ANTICAPTCHA_KEY = "" """ Данная библиотека реализует два различных метода для сохранения изображений(для последующей их передачи сервису): 1. В качестве временного файла, параметр задаётся по умолчанию, но для того что бы его объявить явно нужно передать save_format = 'temp' . 2. В качестве обычного файла, для этого нужно передать: save_format = 'const' . !!!Используйте данный параметр при работе через Windows. USE IT ON WINDOWS!!! """ # Пример который показывает работу антикапчи при решении капчи-изображением и сохранением её в качестве обычного файла в # папку. # Example for working with captcha-image link, and save it like a usual file in system. result = ImageToTextTask.ImageToTextTask(anticaptcha_key=ANTICAPTCHA_KEY, save_format='const') \ .captcha_handler(captcha_link='http://85.255.8.26/static/image/common_image_example/800070.png') print(result) # Пример который показывает работу антикапчи при решении капчи-изображением и сохранением её в качестве ВРЕМЕННОГО файла # Протестировано на Линуксах. Не используйте данный вариант на Windows! Возможно починим, но потом. # Example for working with captcha-image like a temporary file. Tested on UNIX-based systems. Don`t use it on Windows! result = ImageToTextTask.ImageToTextTask(anticaptcha_key=ANTICAPTCHA_KEY) \ .captcha_handler(captcha_link='http://85.255.8.26/static/image/common_image_example/800070.png') print(result) """ Пример работы с передачей файла капчи уже закодированного в base64 """ # закодировано: 976979 base_64_file = open('base64image.txt', 'rb') user_answer_base64 = ImageToTextTask.ImageToTextTask(
def captcha(image_link): ANTICAPTCHA_KEY = "059b63917d2c27b0a6874c943867581d" answer_user = ImageToTextTask.ImageToTextTask( anticaptcha_key=ANTICAPTCHA_KEY).captcha_handler( captcha_link=image_link) return answer_user
2. В качестве обычного файла, для этого нужно передать: save_format = 'const' . ======================================================================================================================== This library implements two different methods for saving images (for their subsequent transfer to the service): 1. As a temporary file, the parameter is set by default: save_format = 'temp'. 2. As a normal file, you need to pass this: save_format = 'const' . """ # Пример который показывает работу антикапчи при решении капчи-изображением и сохранением её в качестве обычного файла в # папку. # Example for working with captcha-image link, and save it like a usual file in system. result = ImageToTextTask.ImageToTextTask( anticaptcha_key=ANTICAPTCHA_KEY, save_format="const" ).captcha_handler( captcha_link="http://85.255.8.26/static/image/common_image_example/800070.png" ) print(result) # Пример который показывает работу антикапчи при решении капчи-изображением и сохранением её в качестве ВРЕМЕННОГО файла # Протестировано на Линуксах. Не используйте данный вариант на Windows! Возможно починим, но потом. # Example for working with captcha-image like a temporary file. Tested on UNIX-based systems. Don`t use it on Windows! result = ImageToTextTask.ImageToTextTask( anticaptcha_key=ANTICAPTCHA_KEY ).captcha_handler( captcha_link="http://85.255.8.26/static/image/common_image_example/800070.png" ) print(result) """
def retrieve_paper(doi, file_name, solve_captcha=False): target = 'http://sci-hub.tw/' + doi response = requests.get(target) soup = bs(response.content, "html.parser") try: mirror = soup.find("iframe", attrs={"id": "pdf"})['src'].split("#")[0] if mirror.startswith('//'): mirror = mirror[2:] mirror = 'https://' + mirror except Exception as ex: logging.error("Mirror not found: %s" % ex) return False try: doi = soup.title.text.split("|")[2].strip() except Exception: logging.error("DOI not found") return False logging.info("Get %s from %s" % (doi, mirror)) response = requests.get(mirror) if response.headers['content-type'] == "application/pdf": logging.info("Downloaded %2.2f MB\n" % (int(response.headers['Content-Length']) / 1000000)) with open(file_name, "wb") as f: f.write(response.content) f.close() return True elif re.match("text/html", response.headers['content-type']): logging.info("Looks like captcha encountered") logging.info("Download link is \n" + mirror + "\n") if not solve_captcha: return mirror captcha = bs(response.content, "html.parser") try: img_url = captcha.find("img", attrs={"id": "captcha"})['src'] except Exception: logging.error("CAPTCHA SOLVING: Cannot get captcha image") return False img_url = 'http://' + mirror[7:].split('/', 2)[0] + img_url logging.info(img_url) r = requests.get(img_url) f = open('/tmp/captcha.jpg', 'wb') f.write(r.content) f.close() user_answer = ImageToTextTask.ImageToTextTask( anticaptcha_key=ANTICAPTCHA_KEY).captcha_handler( captcha_file='/tmp/captcha.jpg' ) # NB *captcha_link* doesn't always work try: solution = user_answer['solution']['text'] except KeyError: logging.error( 'CAPTCHA SOLVING: Unexpected anticaptcha response: %s' % user_answer) return False img_id = img_url.split('/')[-1].replace('.jpg', '') response = requests.post(mirror, data={ 'answer': solution, 'id': img_id }) if response.status_code != 200: logging.error( 'CAPTCHA SOLVING: Anticaptcha gave wrong answer, error %s' % response.status_code) return False if response.headers['content-type'] != "application/pdf": logging.error('CAPTCHA SOLVING: Redirection failed, answer is %s' % response.headers['content-type']) return False logging.info("Downloaded %2.2f MB\n" % (int(response.headers['Content-Length']) / 1000000)) with open(file_name, "wb") as f: f.write(response.content) f.close() return True