예제 #1
0
    def __init__(self, id, log_q):
        Thread.__init__(self)
        self.id = id
        self.log_q = log_q
        self.download_q_override = None
        self.attempts = 0

        self.url = 'http://83.247.110.3/OpenDataHistorie'
        self.open_browser()

        self.api = TwoCaptchaApi('b51dc904b4f0afc3693977440d8e2e02')
예제 #2
0
def solveCaptcha(captcha_file_name):
    # Captcha solved, using third party service
    api = TwoCaptchaApi(captcha_key)
    
    with open(captcha_file_name, 'rb') as captcha_file:
        captcha = api.solve(captcha_file)

    captcha_result = captcha.await_result()
    
    logger.info("Captcha solved: " + captcha_result)
    
    return captcha_result
예제 #3
0
class Captcha(object):
    def __init__(self, captcha):
        self.captcha = captcha
        self.api = TwoCaptchaApi(twocaptcha_api_key)

    def solve(self):
        captcha = self.api.solve(self.captcha)
        return captcha.await_result()
예제 #4
0
def solve_captcha():
    # original from the ipynb
    api = TwoCaptchaApi('')
    print(f"Balance: {api.get_balance()}")

    captcha_image_as_bytes = get_captcha_image()
    print("Got image from project euler")

    captcha = api.solve(BytesIO(captcha_image_as_bytes))
    print("Captcha submitted to 2captcha")

    answer = captcha.await_result()
    print(f"Got the answer: {answer}")

    file_name = f"{img_dir}/{sha1(captcha_image_as_bytes).hexdigest()}_{answer}.jpg"
    with open(file_name, 'wb') as f:
        f.write(captcha_image_as_bytes)
    print(f"Wrote image to {file_name}")
예제 #5
0
def solve_captcha(driver, DOM):
    # Downloads image of
    rect = DOM.rect
    points = [
        rect['x'], rect['y'], rect['x'] + rect['width'],
        rect['y'] + rect['height']
    ]
    with Image.open(StringIO.StringIO(driver.get_screenshot_as_png())) as img:
        with img.crop(points) as imgsub:
            imgsub.save("Proxifier/image.jpeg", 'jpeg')

    captcher = TwoCaptchaApi("133e845b9084b4db3dc5e0e18a0f98ed")
    path = os.path.join(os.path.dirname(os.path.realpath(__file__)),
                        'image.jpeg')
    with open(path, 'rw') as captcha_file:
        captcha = captcher.solve(captcha_file)
    # os.remove(captcha_file)

    return captcha.await_result()
예제 #6
0
 def login_page(self, response):
     try:
         current_url = response.request.url
         print("[Got the Login Page!: {}]".format(current_url))
         captcha_url = response.xpath(
             './/div[@class="image"]/img/@src').extract_first()
         print("[Got the CAPTCHA!: {}]".format(captcha_url))
         login_cap = requests.get(captcha_url, proxies=self.proxy)
         captcha_data = login_cap.content
         with open(self.workDir + '/captcha.jpg', 'wb') as output:
             output.write(captcha_data)
         api = TwoCaptchaApi('cb39bb1f31e79013429c8ef8676b3eb0')
         with open(self.workDir + '/captcha.jpg', 'rb') as captcha_file:
             captcha = api.solve(captcha_file)
             result = captcha.await_result()
         print(result)
         username = response.xpath(
             './/input[@placeholder="Username"]/@name').extract_first()
         password = response.xpath(
             './/input[@placeholder="Password"]/@name').extract_first()
         captcha_f = response.xpath(
             './/input[@placeholder="What\'s the captcha?"]/@name'
         ).extract_first()
         return FormRequest.from_response(response,
                                          formdata={
                                              username: '******',
                                              password: '******',
                                              captcha_f: str(result)
                                          },
                                          clickdata={
                                              'type': 'submit',
                                              'class': 'primary_button'
                                          },
                                          callback=self.home_page)
     except Exception as e:
         print(e)
         print("[Error when handling login form!]")
예제 #7
0
class Processor:

	def __init__(self, user):
		self.user = user
		capthca_api_key = self.user.config.get("twocaptcha_api_key", None)
		self.tcapi = None
		if capthca_api_key:
			self.tcapi  = TwoCaptchaApi(capthca_api_key)


	def process_message(self, message, chatid, userid):
		if not self.tcapi:
			return
		if "captchabalance" in message["body"].lower().encode("utf-8"):
			balance = self.tcapi.get_balance()
			self.user.send_message( text=u"Баланс на каптчарешателе: {}$. В день решается около 300 каптч, 1000 каптч стоит 1$. На сколько этого хватит - посчитаете сами.".format(balance), chatid=chatid, userid=userid)
예제 #8
0
class Processor:
    def __init__(self, user):
        self.user = user
        capthca_api_key = self.user.config.get("twocaptcha_api_key", None)
        self.tcapi = None
        if capthca_api_key:
            self.tcapi = TwoCaptchaApi(capthca_api_key)

    def process_message(self, message, chatid, userid):
        if not self.tcapi:
            return
        if "captchabalance" in message["body"].lower().encode("utf-8"):
            balance = self.tcapi.get_balance()
            self.user.send_message(
                text=
                u"Баланс на каптчарешателе: {}$. В день решается около 300 каптч, 1000 каптч стоит 1$. На сколько этого хватит - посчитаете сами."
                .format(balance),
                chatid=chatid,
                userid=userid)
예제 #9
0
    captcha = api.solve(BytesIO(captcha_image_as_bytes))
    print("Captcha submitted to 2captcha")

    answer = captcha.await_result()
    print(f"Got the answer: {answer}")

    file_name = f"{img_dir}/{sha1(captcha_image_as_bytes).hexdigest()}_{answer}.jpg"
    with open(file_name, 'wb') as f:
        f.write(captcha_image_as_bytes)
    print(f"Wrote image to {file_name}")


if __name__ == "__main__":
    # this could be two separate threads and a redis queue
    # one thread adding captchas to the queue and one checking if they are solved
    api = TwoCaptchaApi(API_KEY)
    print(f"Balance: {api.get_balance()}")

    captchas = []
    for x in range(50):
        try:
            # get captcha image
            captcha_image_as_bytes = get_captcha_image()
            print("Got image from project euler")

            # submit image to 2captcha
            captcha = api.solve(BytesIO(captcha_image_as_bytes))
            print(f"Captcha submitted to 2captcha, {len(captchas) + 1} captchas submitted")

            # add to list of captchas
            captchas.append((captcha, captcha_image_as_bytes))
예제 #10
0
파일: utils.py 프로젝트: Frehsent/tulen
def init_2captcha(api_key):
    global _2captcha_api
    _2captcha_api = TwoCaptchaApi(api_key)
예제 #11
0
 def __init__(self, user):
     self.user = user
     capthca_api_key = self.user.config.get("twocaptcha_api_key", None)
     self.tcapi = None
     if capthca_api_key:
         self.tcapi = TwoCaptchaApi(capthca_api_key)
예제 #12
0
from twocaptchaapi import TwoCaptchaApi
import os
import base64
import requests
import re
import time
s = requests.session()
API_key = "9e8138d9ba14dc"
# API_key="62973dd01dd7"
api = TwoCaptchaApi(API_key)


def base64_text_captcha(base64_url):
    try:
        current_working_dir = os.getcwd()
        base64_image = current_working_dir + "\\" + "sample.png"
        captcha_image = base64.b64decode(base64_url)
        with open(base64_image, "wb") as F:
            F.write(captcha_image)
        raw_input("ch")
        result = text_captcha(base64_image)
        os.remove(base64_image)
        return result
    except Exception as e:
        error = "Error on captcha solving:" + str(e)
        return error


def text_captcha(image):
    try:
        with open(image, 'rb') as captcha_file:
    Module Name: Two_captcha.py
    Created Date: 2018-02-07
    Scope: To solve the text based captcha using 2captcha website .

    Version:V1: 2018-02-07
    Details:
'''

'''two captcha module features from github
   #https://github.com/athre0z/twocaptcha-api'''

from twocaptchaapi import TwoCaptchaApi

# API KEY is generated for the member of 2captcha website.
# api = TwoCaptchaApi('c32f3b1')
api = TwoCaptchaApi('03337')

#list of captcha images
list_image = ["captcha.png", "math.JPG"]


try:
    Balance= (api.get_balance())

    '''check balance in 2captcha source'''
    if float(Balance)==0.0:
        result='Empty'
        raise Exception("OperationFailedError: ERROR_ZERO_BALANCE")
    else:
        for image_1 in list_image:
            #sending the image file to source and solving it
def main():

    workbookRead = xlrd.open_workbook(
        "/Users/rahulbrahmal/Documents/Bot/dsmBot/extraFiles/moreEmails.xls")
    #/Users/rahulbrahmal/Documents/Bot/dsmBot/excelFiles/gmailAccounts.xls
    accounts = workbookRead.sheet_by_index(0)

    workbookPostcodes = xlrd.open_workbook(
        "/Users/rahulbrahmal/Documents/Bot/dsmBot/extraFiles/morePostcodes.xlsx"
    )
    #/Users/rahulbrahmal/Documents/Bot/dsmBot/excelFiles/londonPostcodesCondensed.xlsx
    sheetPostcodes = workbookPostcodes.sheet_by_index(0)

    workbookPhone = xlrd.open_workbook(
        "/Users/rahulbrahmal/Documents/Bot/dsmBot/extraFiles/moreNumbers.xlsx")
    #/Users/rahulbrahmal/Documents/Bot/dsmBot/excelFiles/phoneNumbers.xlsx
    sheetPhone = workbookPhone.sheet_by_index(0)

    chromedriver = "/Users/rahulbrahmal/Documents/Bot/dsmBot/chromedriver"
    os.environ["webdriver.chrome.driver"] = chromedriver
    driver = webdriver.Chrome(chromedriver)
    driver.implicitly_wait(60)

    url = "https://slamjamsocialism-drops.com/drops/8"

    # driver.get(url)

    fileRead = open(
        "/Users/rahulbrahmal/Documents/Bot/dsmBot/extraFiles/neerav500.rtf")
    # #/Users/rahulbrahmal/Documents/Bot/dsmBot/excelFiles/names.rtf
    api = TwoCaptchaApi('9cccbd94c566a11cdb2727a97318748b')
    shoeSize = ""
    shoeIndex = 0
    phoneNumberVal = ""
    lastDigits = 127537
    lastDigitsString = ""
    phoneIndex = 0
    rowRead = 1
    for line in fileRead:
        if (rowRead <= accounts.nrows - 1):

            if (shoeIndex == 0):
                shoeSize = "7"
                shoeIndex = 1
            elif (shoeIndex == 1):
                shoeSize = "8"
                shoeIndex = 2
            elif (shoeIndex == 2):
                shoeSize = "8"
                shoeIndex = 3
            elif (shoeIndex == 3):
                shoeSize = "9"
                shoeIndex = 4
            elif (shoeIndex == 4):
                shoeSize = "9"
                shoeIndex = 5
            elif (shoeIndex == 5):
                shoeSize = "10"
                shoeIndex = 6
            elif (shoeIndex == 6):
                shoeSize = "10"
                shoeIndex = 7
            elif (shoeIndex == 7):
                shoeSize = "11"
                shoeIndex = 8
            elif (shoeIndex == 8):
                shoeSize = "11"
                shoeIndex = 9
            elif (shoeIndex == 9):
                shoeSize = "12"
                shoeIndex = 10
            elif (shoeIndex == 10):
                shoeSize = "7"
                shoeIndex = 0
            # shoeSize = "Size US 8.5"

            lastDigits += 113462
            if (lastDigits > 990000):
                phoneIndex += 1
                lastDigits = 123537 - (8 * rowRead)

            lastDigitsString = str(lastDigits)
            middleDigit = str((sheetPhone.cell_value(rowx=phoneIndex, colx=0)))

            phoneNumberVal = "07" + middleDigit[0:3] + lastDigitsString

            driver.get(url)

            names = line.split(" ")
            print(names[0] + " " + names[1])
            print((accounts.cell_value(rowx=rowRead, colx=0)).lower() +
                  "@gmail.com")
            print(sheetPostcodes.cell_value(rowx=(10 * rowRead), colx=0))
            print(phoneNumberVal)

            driver.implicitly_wait(30)
            nameFirst = driver.find_element_by_xpath(
                '//*[@id="raffle1"]/div[1]/div[1]/input')
            nameFirst.send_keys(names[0])

            nameSecond = driver.find_element_by_xpath(
                '//*[@id="raffle1"]/div[2]/div[1]/input')
            nameSecond.send_keys(names[1])

            email = driver.find_element_by_xpath(
                '//*[@id="raffle1"]/div[3]/div[1]/input')
            emailVal = (accounts.cell_value(rowx=rowRead,
                                            colx=0)).lower() + "@gmail.com"
            email.send_keys(emailVal)

            phoneNumber = driver.find_element_by_xpath(
                '//*[@id="raffle1"]/div[4]/div[1]/input')
            phoneNumber.send_keys(phoneNumberVal)

            countryVal = driver.find_element_by_xpath(
                '//*[@id="raffle1"]/div[5]/div[1]/div/div[1]/div/div/div[1]/input'
            )
            countryVal.send_keys(
                'United Kingdom of Great Britain and Northern Ireland')

            # countryValDropdown = driver.find_element_by_xpath('//*[@id="raffle1"]/div[5]/div[1]/div/ul/li/a/div')
            # countryValDropdown.click()

            city = driver.find_element_by_xpath(
                '//*[@id="raffle1"]/div[6]/div[1]/input')
            city.send_keys("London")

            # postCode = driver.find_element_by_name("Postcode");
            # postCode.send_keys(sheetPostcodes.cell_value(rowx = (10 * rowRead), colx = 0))

            sizeSelection = Select(
                driver.find_element_by_xpath('//*[@id="status"]'))
            sizeSelection.select_by_visible_text(shoeSize)

            # buttonCaptcha = driver.find_element_by_xpath('//*[@id="recaptcha-anchor"]/div[5]')
            # buttonCaptcha.click()

            with open('/my/captcha/path.png', 'rb') as captcha_file:
                captcha = api.solve(captcha_file)

            print(captcha.await_result())

            iframeArr = driver.find_elements_by_xpath(
                '//*[@id="g-recaptcha"]/div/div/iframe')

            # Card Number

            driver.switch_to.frame(iframeArr[0])
            driver.find_element_by_xpath('//*[@id="recaptcha-anchor"]').click()

            driver.switch_to_default_content()

            buttonSubmit = driver.find_element_by_xpath(
                '//*[@id="raffle1"]/input')
            buttonSubmit.click()

            driver.wait(1)

            rowRead += 1

            driver.implicitly_wait(5)

            driver.get(url)

            print(rowRead)
예제 #15
0
class NDWWebBot(Thread):
    def __init__(self, id, log_q):
        Thread.__init__(self)
        self.id = id
        self.log_q = log_q
        self.download_q_override = None
        self.attempts = 0

        self.url = 'http://83.247.110.3/OpenDataHistorie'
        self.open_browser()

        self.api = TwoCaptchaApi('b51dc904b4f0afc3693977440d8e2e02')

    def download(self, link, file_name, chunk_size):
        try:
            if shutil.disk_usage('./')[2] / 1000000000 > 1.4:
                self.__log('Started downloading ' + file_name)
                with urllib.request.urlopen(link,
                                            timeout=10) as response, open(
                                                file_name, 'wb') as out_file:
                    while True:
                        buf = response.read(chunk_size * 1024)
                        if not buf:
                            break
                        out_file.write(buf)
                        out_file.flush()
                        self.__log('Downloaded ' + str(
                            int(os.stat(file_name).st_size / (1024 * 1024))) +
                                   ' MB')
            else:
                self.__log('Not enough space, waiting for 2 minutes')
                time.sleep(120)
                raise Exception('Not an exception')

        except Exception as e:
            self.__log(str(e))
            time.sleep(5)
            self.download(link, file_name, chunk_size)

    def __log(self, message):
        self.log_q.append(
            (self.id, datetime.fromtimestamp(time.time()).strftime('%H:%M:%S'),
             message))

    def open_browser(self):
        self.__log('Opening browser')
        self.browser = webdriver.Chrome(
            "/usr/lib/chromium-browser/chromedriver")
        self.__log('Loading webpage')
        self.browser.get(self.url)
        self.__log('Scrolling down')
        self.browser.execute_script(
            "window.scrollTo(0, document.body.scrollHeight);")

    def at_webform(self):
        try:
            self.browser.find_element_by_id('productId')
            return True
        except NoSuchElementException:
            return False

    def load_webform(self):
        self.__log('Inspecting webform')
        self.datatype = self.browser.find_element_by_id('productId')
        self.start_day = self.browser.find_element_by_id('fromDate')
        self.end_day = self.browser.find_element_by_id('untilDate')
        self.start_hour = self.browser.find_element_by_id('fromTime')
        self.end_hour = self.browser.find_element_by_id('untilTime')
        self.captcha_answer = self.browser.find_element_by_id(
            'CaptchaInputText')

    def fill_form(self, data_type, start_date, end_data):
        self.__log('Filling in the webform')
        self.datatype.send_keys(data_type)
        self.start_day.send_keys(start_date)
        self.end_day.send_keys(end_data)
        self.start_hour.click()
        self.end_hour.click()

    def submit_captcha(self):
        self.captcha_answer.send_keys(Keys.ENTER)

    def reload(self):
        self.__log('Reloading webpage')
        self.browser.get(self.url)
        self.__log('Scrolling down')
        self.browser.execute_script(
            "window.scrollTo(0, document.body.scrollHeight);")

    def get_captcha(self):
        self.__log('Saving screenshot')
        img = self.browser.find_element_by_id('CaptchaImage')
        location, size = img.location_once_scrolled_into_view, img.size
        self.browser.save_screenshot('screenshot' + str(self.id) + '.png')

        self.__log('Locating captcha in screenshot')
        left = location['x']
        top = location['y']
        right = location['x'] + size['width']
        bottom = location['y'] + size['height']

        self.__log('Cropping and saving captcha image')
        im = Image.open('screenshot' + str(self.id) + '.png')
        im = im.crop((left, top, right, bottom))
        im.save('captcha' + str(self.id) + '.png')

    def solve_captcha(self, file_path):
        try:
            self.__log('Solving Captcha')
            with open(file_path, 'rb') as captcha_file:
                captcha = self.api.solve(captcha_file)
            answer = captcha.await_result()
            if len(answer) >= 2:
                return answer
            else:
                raise Exception(answer)
        except Exception as e:
            self.__log(str(e))
            time.sleep(5)
            return self.solve_captcha(file_path)

    def get_link(self):
        try:
            if not self.at_webform():
                link = self.browser.find_element_by_id("link").text
                # Gives exception if link is not clickable
                self.browser.find_element_by_link_text(link)
                return link
            else:
                self.__log('At the wrong page')
                time.sleep(30)
                return self.get_link()

        except Exception as e:
            self.__log('Link still inactive')
            time.sleep(60)
            return self.get_link()

    def check_file(self, file_path):
        try:
            zip = zipfile.ZipFile(file_path)
            if len(zip.filelist) >= (1441 - 1441 * 0.9):
                return 'Good'
            else:
                return 'Bad'
        except Exception as e:
            return 'Bad'

    def run(self):
        while not download_q.empty():
            try:

                self.reload()
                self.load_webform()

                if self.download_q_override is None:
                    folder, data_type, start_date, end_date = download_q.get()
                else:
                    folder, data_type, start_date, end_date = self.download_q_override
                self.__log('Trying ' + data_type + ' ' + start_date)

                self.__log('Looking for webform')
                if self.at_webform():
                    self.fill_form(data_type, start_date, end_date)
                    self.get_captcha()
                    solution = self.solve_captcha('captcha' + str(self.id) +
                                                  '.png')
                    self.captcha_answer.send_keys(solution)
                    self.captcha_answer.send_keys(Keys.ENTER)

                    time.sleep(5)
                    if self.at_webform():
                        self.download_q_override = folder, data_type, start_date, end_date
                        raise Exception('Wrong Captcha answer')

                else:
                    self.__log('Not at webform')
                    self.download_q_override = folder, data_type, start_date, end_date
                    raise Exception('Wrong Captcha answer')

                link = self.get_link()
                if data_type == 'Reistijden':
                    file_name = 'r' + start_date + '.zip'
                else:
                    file_name = start_date + '.zip'

                self.download(link, file_name=file_name, chunk_size=1024 * 25)
                if self.check_file(file_name) != 'Good':
                    self.download_q_override = folder, data_type, start_date, end_date
                    raise Exception(
                        'Corrupted or incomplete zip, F**K YOU NDW!')
                else:
                    self.download_q_override = None

                upload_q.put((folder, file_name))
                time.sleep(30)

            except Exception as e:
                self.__log(str(e))
                time.sleep(30)
예제 #16
0
	def __init__(self, user):
		self.user = user
		capthca_api_key = self.user.config.get("twocaptcha_api_key", None)
		self.tcapi = None
		if capthca_api_key:
			self.tcapi  = TwoCaptchaApi(capthca_api_key)
예제 #17
0
파일: scrap.py 프로젝트: dkabulski/onedrive
from selenium import webdriver
import string, random, names, time, re, urllib
from twocaptchaapi import TwoCaptchaApi
api = TwoCaptchaApi('API KEY HERE')
png = 'captch.jpg'
days = random.randint(0, 27)
months = [
    'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct',
    'Nov', 'Dec'
]


def urs_generator(size=5, chars=string.digits + string.digits):  # +
    return ''.join(random.choice(chars) for _ in range(size))


def pwd_generator(size=10,
                  chars=string.ascii_uppercase + string.digits +
                  string.punctuation):  # + string.digits
    return ''.join(random.choice(chars) for _ in range(size))


def onedrive_utm(utm_link):
    # utm_link = 'https://onedrive.live.com?invref=e9f36c73a3e0ddc9&invscr=90'
    browser = webdriver.Chrome(
        executable_path=
        r'C:\Users\Oladimeji Olaolorun\github\Projects\chromedriver.exe')
    browser.maximize_window()
    browser.get(utm_link)
    time.sleep(3)
    username = browser.find_element_by_id('signup').click()
예제 #18
0
 def __init__(self, captcha):
     self.captcha = captcha
     self.api = TwoCaptchaApi(twocaptcha_api_key)
예제 #19
0
import requests
import time
import re
import xlwt
from twocaptchaapi import TwoCaptchaApi
from datetime import datetime
from dateutil.relativedelta import relativedelta

# sheet1.write(0, 0, "Date")

api = TwoCaptchaApi('18c788d0897708ea27a0207871f')


def Capcha_Convert(capcha_image):
    try:
        Balance = (api.get_balance())
        '''check balance in 2captcha source'''
        if float(Balance) == 0.0:
            result = 'Empty'
            raise Exception("OperationFailedError: ERROR_ZERO_BALANCE")
        else:
            with open(capcha_image, 'rb') as captcha_file:
                captcha = api.solve(captcha_file)
            try:
                result = captcha.await_result()
                print "result", result
                print "%s == %s" % (capcha_image, result)
                return result
            except Exception as e:
                print "Error", str(e)
예제 #20
0
from bs4 import BeautifulSoup
from json import load
import json
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait, Select
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.keys import Keys
from twocaptchaapi import TwoCaptchaApi
from PIL import Image
from pprint import pprint



api = TwoCaptchaApi('2b67434ad6039b2c71cb986d1e4d7ca6')
fileName = "{}.csv".format(time())
captcha_filename = "captcha/" + "{}.png".format(time())


#Load login details and search query data
with open("login_details.txt") as r:
    auth = load(r)

user_id = auth['USERNAME']
pwd = auth['PASSWORD']
wait_more = float(auth['LAZY_LOGIN'])
wait_less =float(auth['LAZY_FORM'])

with open("luxsocks.csv", "r") as f:
    rows = f.read().split("\n")