예제 #1
0
파일: gui.py 프로젝트: mirth/captcha_solver
class GuiTestCase(TestCase):

    def setUp(self):
        self.solver = CaptchaSolver('gui')
        self.cw_patcher = patch('captcha_solver.captcha_backend'
                                '.gui.CaptchaWindow')
        self.mock_cw = self.cw_patcher.start()

    def tearDown(self):
        self.cw_patcher.stop()

    def test_captcha_decoded(self):

        class MockCW(object):
            def __init__(self, path, solution):
                self.solution = solution
                self.solution.append('decoded_captcha')

            def main(self):
                pass

        self.mock_cw.side_effect = MockCW

        self.assertEqual(self.solver.solve_captcha(b'image_data'),
                         'decoded_captcha')
예제 #2
0
def create_group(chat_title):
    chat_title = "MEOW" + str(chat_title)
    try:
        thischat = api.messages.createChat(user_ids=chat_users_list,
                                           title=chat_title,
                                           v=APIVersion)
        api.messages.removeChatUser(chat_id=thischat,
                                    user_id=334479550,
                                    v=APIVersion)

    except Exception as e:
        captcha_sid = vk.exceptions.VkAPIError.captcha_sid.__get__(e)
        captcha_url = vk.exceptions.VkAPIError.captcha_img.__get__(e)
        if (captcha_sid == None) and (captcha_url == None):
            time.sleep(3)
            api.messages.createChat(user_ids=chat_users_list,
                                    title=chat_title,
                                    v=APIVersion)
        requests_image(captcha_url)
        solver = CaptchaSolver("antigate", api_key=antigate_token)
        raw_data = open("captchaGROUP.jpg", "rb").read()
        captcha_ready = solver.solve_captcha(raw_data)
        print(captcha_ready)
        api.messages.createChat(
            user_ids=chat_users_list,
            title=chat_title,
            v=APIVersion,
            captcha_sid=captcha_sid,
            captcha_key=captcha_ready,
        )
예제 #3
0
def add_audio(access_token, audio_id, owner_id):
    global headers
    response = requests.get(
        "https://api.vk.com/method/audio.add?access_token=" + access_token +
        "&audio_id=" + str(audio_id) + "&owner_id=" + str(owner_id) +
        "&v=5.71",
        headers=headers,
        verify=False,
    ).json()
    try:
        print(response["response"])
    except:
        print("****Капча на add_audio****\n" +
              response["error"]["captcha_img"])
        captcha_sid = response["error"]["captcha_sid"]
        requests_image(response["error"]["captcha_img"])
        solver = CaptchaSolver("antigate", api_key=antigate_token)
        raw_data = open("captcha.jpg", "rb").read()
        captcha_ready = solver.solve_captcha(raw_data)
        print(captcha_ready)
        print("Пробуем..")

        check = requests.get(
            "https://api.vk.com/method/audio.add?access_token=" +
            access_token + "&audio_id=" + str(audio_id) + "&owner_id=" +
            str(owner_id) + "&v=5.71&captcha_sid=" + captcha_sid +
            "&captcha_key=" + captcha_ready,
            headers=headers,
            verify=False,
        ).json()

        if check["response"] != None:
            print("Все успешно!")
예제 #4
0
def book(s, list_booking):
    to_book = None
    for booking in list_booking:
        if booking['hour'] == '20':
            to_book = booking
            break

    if to_book != None:
        payload = {'cle': to_book['payload']}
        rep = s.post(
            'https://teleservices.paris.fr/srtm/reservationCreneauReserver.action',
            data=payload)

        captcha = s.get('https://teleservices.paris.fr/srtm/ImageCaptcha'
                        ).text.encode('ISO-8859-1')
        solver = CaptchaSolver('browser')
        payload['jcaptcha_reponse'] = solver.solve_captcha(captcha)
        payload['valider'] = 'ENREGISTRER'
        rep = s.post(
            'https://teleservices.paris.fr/srtm/ReservationCreneauValidationForm.action',
            data=payload)

        if rep.ok:
            print 'Book done in %s the %s at %sh' % (
                to_book['short'], to_book['date'], to_book['hour'])
        else:
            print 'Fail booking'
    else:
        print 'No book found'
예제 #5
0
 def solve_captcha(self):
     if not self.captcha_img_el:
         return
     captcha_solver = CaptchaSolver('rucaptcha', api_key=RUCAPTCHA_API_KEY)
     img_path = os.path.join(os.getcwd(), 'captcha.png')
     self.captcha_img_el.screenshot(img_path)
     key = captcha_solver.solve_captcha(open(img_path, mode='rb').read())
     self.captcha_input_el.send_keys(key)
예제 #6
0
def captcha_solve(url, key):
    if key is not None:
        try:
            solver = CaptchaSolver('antigate', api_key=key)
            raw_data = requests.get(url, stream=True).raw.read()
            key = solver.solve_captcha(raw_data)
            return key
        except Exception as e:
            print("Exception: ", e)
    return None
예제 #7
0
    def _resolve_captcha(self, image_url):
        image_bytes = requests.get(image_url).content
        image = Image.open(BytesIO(image_bytes))
        w, h = image.size
        image = image.crop((0, 0, w, h - 12))
        image.save('tmp/captcha.jpg')

        image_bytes = BytesIO()
        image.save(image_bytes, format='JPEG')
        image_bytes = image_bytes.getvalue()

        solver = CaptchaSolver('rucaptcha', api_key=RutrackerParser.RUCAPTCHA_KEY)
        result = solver.solve_captcha(image_bytes)
        return result
def break_captcha(driver):
    #get captcha image
    try:
        img = driver.find_element_by_class_name("captcha__image")
        src = img.get_attribute('src')
        urllib.request.urlretrieve(src, "captcha.png")

        solver = CaptchaSolver('rucaptcha',
                               api_key='bef7004b9dcbbcba502cd826f2bafa49')
        raw_data = open('captcha.png', 'rb').read()
        captcha_text = solver.solve_captcha(raw_data)
    except captcha_solver.error.CaptchaServiceError:
        driver.find_element_by_class_name("captcha__image").click()
        break_captcha(driver)
    return captcha_text
예제 #9
0
    def captcha_handler(captcha):
        from Settings import RUCAPTCHA_KEY

        url = captcha.get_url()

        image_url = requests.get(url)
        img = image_url.content

        file = open('tmp.jpg', "wb")
        file.write(img)
        file.close()

        solver = CaptchaSolver('rucaptcha', api_key=RUCAPTCHA_KEY)
        raw_data = open('tmp.jpg', 'rb').read()

        return captcha.try_again(solver.solve_captcha(raw_data))
예제 #10
0
 def __solve_captcha(captcha_url: str):
     """
     downloads captcha image and send to 2captcha to solve
     :param captcha_url: Captcha image url
     :return: string with captcha solution
     """
     img_name = f'{uuid4()}.jpg'
     if OutlookAccountCreator.__download_image(captcha_url, img_name):
         print('Solving Captcha...')
         solver = CaptchaSolver('2captcha', api_key=API_2_CAPTCHA)
         raw_data = open(img_name, 'rb').read()
         solution = solver.solve_captcha(raw_data)
         os.remove(img_name)
         print(f"Captcha solved (solution: {solution})...")
         return solution
     print('Failed to download captcha image...')
예제 #11
0
    def getRuCaptchaSolver(self, filename):
        """

        :param filename: - Имя файла с фотографией капчи
        :return: - Вернет саму отгадку капчи
        """

        while True:
            try:
                solver = CaptchaSolver('rucaptcha', api_key=self.rucaptcha_key)
                raw_data = open(filename, 'rb').read()

                return solver.solve_captcha(raw_data)

            except:
                pass
예제 #12
0
    def resolveNormalCaptcha(self, image_path, retry=5):
        if not self._api_key:
            logging.info("No 2captcha API key")
            return None

        while retry > 0:
            try:
                raw_data = open(image_path, 'rb').read()
                logging.info("Resolving captcha...")
                solver = CaptchaSolver('2captcha', api_key=self._api_key)
                captcha_code = solver.solve_captcha(raw_data)
                logging.info('Captcha code is:{}'.format(captcha_code))

                return captcha_code
            except print(0):
                pass
        return None
예제 #13
0
class BrowserTestCase(TestCase):
    def setUp(self):
        self.solver = CaptchaSolver('browser')
        self.wb_patcher = patch('webbrowser.open')
        self.mock_wb_open = self.wb_patcher.start()
        self.raw_input_patcher = patch('captcha_solver.backend.browser.input')
        self.mock_raw_input = self.raw_input_patcher.start()

    def tearDown(self):
        self.wb_patcher.stop()
        self.raw_input_patcher.stop()

    def test_captcha_decoded(self):
        self.mock_wb_open.return_value = None
        self.mock_raw_input.return_value = 'decoded_captcha'

        self.assertEqual(self.solver.solve_captcha(b'image_data'),
                         'decoded_captcha')
예제 #14
0
class BrowserTestCase(TestCase):

    def setUp(self):
        self.solver = CaptchaSolver('browser')
        self.wb_patcher = patch('webbrowser.open')
        self.mock_wb_open = self.wb_patcher.start()
        self.raw_input_patcher = patch('captcha_solver.captcha_backend'
                                       '.browser.input')
        self.mock_raw_input = self.raw_input_patcher.start()

    def tearDown(self):
        self.wb_patcher.stop()
        self.raw_input_patcher.stop()

    def test_captcha_decoded(self):
        self.mock_wb_open.return_value = None
        self.mock_raw_input.return_value = 'decoded_captcha'

        self.assertEqual(self.solver.solve_captcha(b'image_data'),
                         'decoded_captcha')
예제 #15
0
    def solve_captcha(self, response):
        if os.environ.get('ANTICAPTCHA_API_KEY'):
            solver = CaptchaSolver('antigate',
                                   api_key=os.environ['ANTICAPTCHA_API_KEY'])
        else:
            solver = CaptchaSolver('browser')

        # Can fetch this a few time and get different randomly-generated captchas to help make a better guess.
        # See: https://ereg.elections.ca/Telerik.Web.UI.WebResource.axd?type=rca&isc=true&guid=2d918a7f-09cb-4e0e-92e2-125d4ddb156a
        captcha_path = response.css(
            '#ctl00_ContentPlaceHolder1_RadCaptcha1_CaptchaImage::attr(src)'
        ).extract_first()
        captcha_url = 'https://ereg.elections.ca/{}'.format(captcha_path)
        jpg_data = urllib.request.urlopen(captcha_url).read()

        self.crawler.engine.pause()
        captcha = solver.solve_captcha(jpg_data)
        self.crawler.engine.unpause()

        formdata = {
            '__EVENTTARGET':
            '',
            '__EVENTARGUMENT':
            '',
            '__VIEWSTATE':
            response.css('#__VIEWSTATE::attr(value)').extract_first(),
            '__EVENTVALIDATION':
            response.css('#__EVENTVALIDATION::attr(value)').extract_first(),
            'ctl00$ContentPlaceHolder1$txtCaptcha':
            captcha,
        }
        yield FormRequest.from_response(
            response,
            formdata=formdata,
            formcss='#form1',
            clickdata={
                'name': 'ctl00$ContentPlaceHolder1$NavButton$BtnNextDelay'
            },
            callback=self.parse_vote_eligibility,
        )
예제 #16
0
class GuiTestCase(TestCase):
    def setUp(self):
        self.solver = CaptchaSolver('gui')
        self.cw_patcher = patch('captcha_solver.backend.gui.CaptchaWindow')
        self.mock_cw = self.cw_patcher.start()

    def tearDown(self):
        self.cw_patcher.stop()

    def test_captcha_decoded(self):
        class MockCW(object):
            def __init__(self, path, solution):
                self.solution = solution
                self.solution.append('decoded_captcha')

            def main(self):
                pass

        self.mock_cw.side_effect = MockCW

        self.assertEqual(self.solver.solve_captcha(b'image_data'),
                         'decoded_captcha')
예제 #17
0
    def _bake_captcha(self, comment_block):
        import requests
        from requests.exceptions import InvalidURL
        from captcha_solver import CaptchaSolver

        url_image = comment_block.element("img#captcha").src
        try:
            get_img = requests.get(url_image, stream=True)
        except InvalidURL:
            capthca_url_without_auth = url_image.replace('t:123456%@',
                                                         '') + '.jpeg'
            get_img = requests.get(capthca_url_without_auth,
                                   stream=True,
                                   auth=('t', '123456%'))

        with open('captcha_rating.jpeg', 'wb') as fd:
            for chunk in get_img.iter_content(chunk_size=128):
                fd.write(chunk)
        solver = CaptchaSolver('antigate',
                               api_key='3d756e5391dd1e1423739217e6579c1a')
        raw_data = open('captcha_rating.jpeg', 'rb').read()

        return solver.solve_captcha(raw_data)
예제 #18
0
def handle_captcha(res):
    if 'validateCaptcha' not in res.text:
        return res
    print '='*78
    with open('captcha.html', 'w') as file:
        file.write(res.content)
    soup = BeautifulSoup(res.text, 'html.parser')
    elems = soup.select('form img')
    fields = {
        elem.attrs['name']: elem.attrs['value']
        for elem in soup.select('form input[type="hidden"]')
    }
    print 'Image: ' + elems[0].attrs['src']
    img = session.get(elems[0].attrs['src'])
    with open('captcha.jpg', 'wb') as file:
        file.write(img.content)
    solver = CaptchaSolver('browser')
    fields['field-keywords'] = solver.solve_captcha(img.content).upper()
    res = session.get(
        'https://www.amazon.de/errors/validateCaptcha',
        params=fields)
    print '='*78
    return handle_captcha(res)
예제 #19
0
from captcha_solver import CaptchaSolver
solver=CaptchaSolver('browser')
with open('/images/sbi.png','rb') as inp:
	raw_data=inp.read()
print(solver.solve_captcha(raw_data))
  
예제 #20
0
driver.find_element_by_id('ap_password').send_keys(password)
driver.find_element_by_id('ap_password_check').send_keys(password)
driver.find_element_by_xpath("//*[@id='continue']").click()

try: # to bypass the captcha code
    from captcha_solver import CaptchaSolver
    from io import BytesIO
    from PIL import Image
    element = driver.find_element_by_xpath("//img[@id='auth-captcha-image']")
    png = driver.get_screenshot_as_png()
    im = Image.open(BytesIO(png))
    im = im.crop((1000,1190,1380,1330))
    im.save('captcha.png')
    solver = CaptchaSolver('antigate', api_key='18ebda48664c28ce6ebc86baa3701579')
    captcha = open('captcha.png', 'rb').read()
    captchaCode = solver.solve_captcha(captcha) # solves the captcha puzzle
    driver.find_element_by_xpath("//*[@id='auth-captcha-guess']").send_keys(captchaCode)
    driver.find_element_by_id('ap_password').send_keys(password)
    driver.find_element_by_id('ap_password_check').send_keys(password)
    driver.find_element_by_xpath("//*[@id='continue']").click()
except NoSuchElementException: # unless there isn't a captcha code
    pass

# pass the next page
driver.switch_to.window(driver.window_handles[-1])
driver.find_element_by_xpath("//*[@id='payments_widget_add_credit_card_number']").send_keys(creditCard)
driver.find_element_by_xpath("//select[@name='expirationMonth']/option[@value='11']").click()
driver.find_element_by_xpath("//select[@name='expirationYear']/option[@value='2021']").click()
driver.find_element_by_xpath("//*[@id='payments_widget_full_name']").send_keys(name)
driver.find_element_by_xpath("//*[@id='payments_widget_address_line_1']").send_keys(street)
driver.find_element_by_xpath("//*[@id='payments_widget_zip_code']").send_keys(zipcode)
예제 #21
0
        #Если надо, то меняем название
		if check != chat_titles[str(i+1)]:
			try:
				api.messages.editChat(chat_id=conf_id,title=chat_titles[str(i+1)],v=APIVersion)
			except Exception as e:

				captcha_sid=vk.exceptions.VkAPIError.captcha_sid.__get__(e)
				captcha_url = vk.exceptions.VkAPIError.captcha_img.__get__(e)
				if (captcha_sid == None) and (captcha_url == None):
					time.sleep(3)
					api.messages.editChat(chat_id=conf_id,title=chat_titles[str(i+1)],v=APIVersion)
				requests_image(captcha_url)
				solver = CaptchaSolver('antigate', api_key=antigate_token)
				raw_data = open('captcha.jpg', 'rb').read()
				captcha_ready = solver.solve_captcha(raw_data)
				api.messages.editChat(chat_id=conf_id,title=chat_titles[str(i+1)],v=APIVersion,captcha_sid=captcha_sid,captcha_key=captcha_ready)
	checker = False

	for i in range(len(response['updates'])):
		if checker != True:
			try:

				message_longpoll = response['updates'][i][5]
				chat_longpoll = response['updates'][i][3]-2000000000
				checker = True

			except:
				pass
	if checker == False:
		message_longpoll = [0]
예제 #22
0
def checkpromo():
    driver.get('https://dodopizza.ru/peterburg')
    input('Enter?')
    driver.get('https://dodopizza.ru/peterburg/cart')
    time.sleep(5)
    driver.find_element_by_xpath(
        '//*[@id="react-app"]/main/section[3]/div/div/div/input').send_keys(
            '7024C7EA4\n')
    url = input('Введите url captha: ')
    image = urlopen(url).read()
    with open("image.png", "wb") as f:
        f.write(image)
    im = Image.open("image.png")
    x = (im.size[0])
    print('Size: ' + str(x))
    solver = CaptchaSolver('rucaptcha', api_key='#########')
    raw_data = open('image.png', 'rb').read()
    solve = (solver.solve_captcha(raw_data))
    print(solve)
    array = []
    for i in range(len(solve)):
        array.append(int(solve[i]))
    if x == 300:
        for i in array:
            if i == 1:
                pyautogui.moveTo(550, 330)
                pyautogui.click()
            elif i == 2:
                pyautogui.moveTo(680, 330)
                pyautogui.click()
            elif i == 3:
                pyautogui.moveTo(800, 330)
                pyautogui.click()
            elif i == 4:
                pyautogui.moveTo(550, 450)
                pyautogui.click()
            elif i == 5:
                pyautogui.moveTo(680, 450)
                pyautogui.click()
            elif i == 6:
                pyautogui.moveTo(800, 450)
                pyautogui.click()
            elif i == 7:
                pyautogui.moveTo(550, 590)
                pyautogui.click()
            elif i == 8:
                pyautogui.moveTo(680, 590)
                pyautogui.click()
            elif i == 9:
                pyautogui.moveTo(800, 590)
                pyautogui.click()
            time.sleep(1)
    if x == 450:
        for i in array:
            if i == 1:
                pyautogui.moveTo(530, 310)
                pyautogui.click()
            elif i == 2:
                pyautogui.moveTo(630, 310)
                pyautogui.click()
            elif i == 3:
                pyautogui.moveTo(730, 310)
                pyautogui.click()
            elif i == 4:
                pyautogui.moveTo(830, 310)
                pyautogui.click()
            elif i == 5:
                pyautogui.moveTo(530, 405)
                pyautogui.click()
            elif i == 6:
                pyautogui.moveTo(630, 405)
                pyautogui.click()
            elif i == 7:
                pyautogui.moveTo(730, 405)
                pyautogui.click()
            elif i == 8:
                pyautogui.moveTo(830, 405)
                pyautogui.click()
            elif i == 9:
                pyautogui.moveTo(530, 500)
                pyautogui.click()
            elif i == 10:
                pyautogui.moveTo(630, 500)
                pyautogui.click()
            elif i == 11:
                pyautogui.moveTo(730, 500)
                pyautogui.click()
            elif i == 12:
                pyautogui.moveTo(830, 500)
                pyautogui.click()
            elif i == 13:
                pyautogui.moveTo(530, 600)
                pyautogui.click()
            elif i == 14:
                pyautogui.moveTo(630, 600)
                pyautogui.click()
            elif i == 15:
                pyautogui.moveTo(730, 600)
                pyautogui.click()
            elif i == 16:
                pyautogui.moveTo(830, 600)
                pyautogui.click()
    input('end')
    html = driver.page_source
    soup = BeautifulSoup(html, "html.parser")
    with open("soup.txt", "w", encoding="UTF-8") as file:
        file.write(str(soup))
예제 #23
0
def captcha_solver(data):
    solver = CaptchaSolver('antigate', api_key=settings.ANTICAPTCHA_KEY)
    return solver.solve_captcha(data)
예제 #24
0
class AntigateUrllibTestCase(BaseSolverTestCase):
    def setup_solver(self):
        self.solver = CaptchaSolver('antigate',
                                    network_backend='urllib',
                                    service_url=self.server.get_url(),
                                    api_key='does not matter')

    def test_post_data(self):
        data = b'foo'
        res = self.solver.captcha_backend.get_submit_captcha_request_data(data)
        body = res['post_data']['body']

        self.assertTrue(isinstance(body, string_types))

    def test_antigate_decoded(self):
        def handler():
            yield b'OK|captcha_id'
            yield b'OK|decoded_captcha'

        self.server.response['data'] = handler()
        self.assertEqual(self.solver.solve_captcha(b'image_data'),
                         'decoded_captcha')

    def test_antigate_no_slot_available(self):
        self.server.response_once['data'] = b'ERROR_NO_SLOT_AVAILABLE'
        self.assertRaises(SolutionTimeoutError, self.solver.solve_captcha,
                          b'image_data', **NO_DELAY)

    def test_antigate_zero_balance(self):
        self.server.response_once['data'] = b'ERROR_ZERO_BALANCE'
        self.assertRaises(BalanceTooLow, self.solver.solve_captcha,
                          b'image_data')

    def test_antigate_unknown_error(self):
        self.server.response_once['data'] = b'UNKNOWN_ERROR'
        self.assertRaises(CaptchaServiceError, self.solver.solve_captcha,
                          b'image_data')

    def test_antigate_unknown_code(self):
        self.server.response_once['code'] = 404
        self.assertRaises(CaptchaServiceError, self.solver.solve_captcha,
                          b'image_data')

    def test_solution_timeout_error(self):
        def handler():
            yield b'OK|captcha_id'
            yield b'CAPCHA_NOT_READY'

        self.server.response['data'] = handler()
        self.assertRaises(SolutionTimeoutError, self.solver.solve_captcha,
                          b'image_data', **NO_DELAY)

    def test_solution_unknown_error(self):
        def handler():
            yield b'OK|captcha_id'
            yield b'UNKNOWN_ERROR'

        self.server.response['data'] = handler()
        self.assertRaises(CaptchaServiceError, self.solver.solve_captcha,
                          b'image_data', **NO_DELAY)

    def test_solution_unknown_code(self):
        def handler():
            yield b'OK|captcha_id'

        self.server.response['data'] = handler()
        self.assertRaises(CaptchaServiceError, self.solver.solve_captcha,
                          b'image_data', **NO_DELAY)
예제 #25
0
def main():
    solver = CaptchaSolver('browser')
    with open('gpin.jpg', 'rb') as inp:
        raw_data = inp.read()
        print(raw_data.decode("utf-8"))
        print(solver.solve_captcha(raw_data))
예제 #26
0
def solveCaptcha(img):
	image = cv2.imread(img)
	gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
	solver = CaptchaSolver('browser')
	print(solver.solve_captcha(gray))
예제 #27
0
import os
from captcha_solver import CaptchaSolver

with open('sbi.jpg', 'rb') as inp:
    raw_data = inp.read()

solver = CaptchaSolver('browser')
#print str(os.listdir())

decoded = solver.solve_captcha(raw_data)
print "Decoded is :" + str(decoded)
예제 #28
0
def decode():
    solver = CaptchaSolver('browser')
    with open('test.jpg', 'rb') as inp:
        raw_data = inp.read()
    print(solver.solve_captcha(raw_data))
예제 #29
0
#1.關閉說明浮動選單
sleep(2)
dialog_close = driver.find_element_by_class_name(
    'ui-dialog-titlebar-close').click()

#2.選不動產買買
sleep(2)
land_sale = driver.find_element_by_xpath(
    '//div[@class="main_menu"]/ul[@class="sale"]/li/a[@id="land"]').click()

#3.通過圖形驗證
sleep(2)
checknum = driver.find_element_by_xpath('//span[@id="checknum_pan"]/img')
checknum.screenshot('captcha_image.png')
raw_data = open('captcha_image.png', 'rb').read()
captcha_code = solver.solve_captcha(raw_data)

code = driver.find_element_by_xpath('//input[@name="rand_code"]')
code.clear()
code.send_keys(captcha_code)

confirm = driver.find_element_by_xpath('//img[@name="Image2"]').click()

#關閉提示
sleep(2)
dialog_close = driver.find_element_by_class_name('close_btn').click()

#進入區域查詢畫面
sleep(2)
city = Select(driver.find_element_by_name('Qry_city'))
area = Select(driver.find_element_by_name('Qry_area_office'))
예제 #30
0
# Open first page
response = br.open(home_url)

# Find CAPTCHA URL and download the image file
html1 = response.read()
page = BeautifulSoup(html1, "lxml")
end_img_url = page.findAll("img")[0].attrs["src"][2:]
captcha_url = base_img_url + end_img_url
br.retrieve(captcha_url, captcha_file)

# Manually solve the captcha
print "Please enter below the number shown in the viewer window:"
solver = CaptchaSolver("browser")
with open(captcha_file, "rb") as f:
    raw_data = f.read()
captcha_solution = solver.solve_captcha(raw_data)

# Submit form to search for funds
br.select_form(nr=0)
br.set_all_readonly(False)
br.form["txtCNPJNome"] = cnpj
br.form["ddlTpFdo"] = 0
br.form["numRandom"] = captcha_solution

sleep(1)
response = br.submit()

# Select fund on search results list
# To simulate the __doPostBack javascript function behaviour, we take its
# parameters and use them as the values for the inputs __EVENTTARGET and __EVENTARGUMENT
html2 = response.read()
예제 #31
0
def solve_captcha():
    solver =CaptchaSolver('browser')
    imgdata = requests.get("http://xk.fudan.edu.cn/xk/captcha/image.action?d=" + time.time(), cookies=coo,headers=loginheaders)
    print(imgdata.headers)
    ans=solver.solve_captcha(imgdata.content)
    return ans
예제 #32
0
import json
import uuid

import requests
from captcha_solver import CaptchaSolver

try:
    data = json.loads(open('data.json').read())
except:
    data = []

solver = CaptchaSolver('browser')
while True:
    pic = requests.get(
        'https://course.nctu.edu.tw/function/Safecode.asp').content
    ans = solver.solve_captcha(pic)
    filename = '%s.png' % str(uuid.uuid4())
    print(ans)
    with open(filename, 'wb') as f:
        f.write(pic)
    data.append((ans, filename))
    with open('data.json', 'w') as f:
        f.write(json.dumps(data))
예제 #33
0
# Open first page
response = br.open(home_url)

# Find CAPTCHA URL and download the image file
html1 = response.read()
page = BeautifulSoup(html1, "lxml")
end_img_url = page.findAll("img")[0].attrs["src"][2:]
captcha_url = base_img_url + end_img_url
br.retrieve(captcha_url, captcha_file)

# Manually solve the captcha
print "Please enter below the number shown in the viewer window:"
solver = CaptchaSolver("browser")
with open(captcha_file, "rb") as f:
    raw_data = f.read()
captcha_solution = solver.solve_captcha(raw_data)

# Submit form to search for funds
br.select_form(nr=0)
br.set_all_readonly(False)
br.form["txtCNPJNome"] = cnpj
br.form["ddlTpFdo"] = 0
br.form["numRandom"] = captcha_solution

sleep(1)
response = br.submit()

# Select fund on search results list
# To simulate the __doPostBack javascript function behaviour, we take its
# parameters and use them as the values for the inputs __EVENTTARGET and __EVENTARGUMENT
html2 = response.read()