1from __future__ import absolute_import 2from ..exceptions import ( 3 CaptchaParameter, 4 CaptchaTimeout, 5 CaptchaAPIError 6) 7 8try: 9 from urlparse import urlparse 10except ImportError: 11 from urllib.parse import urlparse 12 13try: 14 from python_anticaptcha import ( 15 AnticaptchaClient, 16 NoCaptchaTaskProxylessTask, 17 HCaptchaTaskProxyless, 18 NoCaptchaTask, 19 HCaptchaTask, 20 AnticaptchaException 21 ) 22except ImportError: 23 raise ImportError( 24 "Please install/upgrade the python module 'python_anticaptcha' via " 25 "pip install python-anticaptcha or https://github.com/ad-m/python-anticaptcha/" 26 ) 27 28import sys 29 30from . import Captcha 31 32 33class captchaSolver(Captcha): 34 35 def __init__(self): 36 if sys.modules['python_anticaptcha'].__version__ < '0.6': 37 raise ImportError( 38 "Please upgrade the python module 'python_anticaptcha' via " 39 "pip install -U python-anticaptcha or https://github.com/ad-m/python-anticaptcha/" 40 ) 41 super(captchaSolver, self).__init__('anticaptcha') 42 43 # ------------------------------------------------------------------------------- # 44 45 def parseProxy(self, url, user_agent): 46 parsed = urlparse(url) 47 48 return dict( 49 proxy_type=parsed.scheme, 50 proxy_address=parsed.hostname, 51 proxy_port=parsed.port, 52 proxy_login=parsed.username, 53 proxy_password=parsed.password, 54 user_agent=user_agent 55 ) 56 57 # ------------------------------------------------------------------------------- # 58 59 def getCaptchaAnswer(self, captchaType, url, siteKey, captchaParams): 60 if not captchaParams.get('api_key'): 61 raise CaptchaParameter("anticaptcha: Missing api_key parameter.") 62 63 client = AnticaptchaClient(captchaParams.get('api_key')) 64 65 if captchaParams.get('proxy') and not captchaParams.get('no_proxy'): 66 captchaMap = { 67 'reCaptcha': NoCaptchaTask, 68 'hCaptcha': HCaptchaTask 69 } 70 71 proxy = self.parseProxy( 72 captchaParams.get('proxy', {}).get('https'), 73 captchaParams.get('User-Agent', '') 74 ) 75 76 task = captchaMap[captchaType]( 77 url, 78 siteKey, 79 **proxy 80 ) 81 else: 82 captchaMap = { 83 'reCaptcha': NoCaptchaTaskProxylessTask, 84 'hCaptcha': HCaptchaTaskProxyless 85 } 86 task = captchaMap[captchaType](url, siteKey) 87 88 if not hasattr(client, 'createTaskSmee'): 89 raise NotImplementedError( 90 "Please upgrade 'python_anticaptcha' via pip or download it from " 91 "https://github.com/ad-m/python-anticaptcha/tree/hcaptcha" 92 ) 93 94 job = client.createTaskSmee(task, timeout=180) 95 96 try: 97 job.join(maximum_time=180) 98 except (AnticaptchaException) as e: 99 raise CaptchaTimeout(f"{getattr(e, 'message', e)}") 100 101 if 'solution' in job._last_result: 102 return job.get_solution_response() 103 else: 104 raise CaptchaAPIError('Job did not return `solution` key in payload.') 105 106 107# ------------------------------------------------------------------------------- # 108 109captchaSolver() 110