From efa42052fb2ad4af25975c8ab7f9c5965bb0d8bb Mon Sep 17 00:00:00 2001 From: Maxim S Date: Thu, 21 Nov 2024 12:03:57 +0100 Subject: [PATCH] - Added keycaptcha example --- examples/hCaptcha/hcaptcha.py | 130 ------------------ examples/hCaptcha/hcaptcha_proxy.py | 139 ------------------- examples/keycaptcha/keycaptcha.py | 203 ++++++++++++++++++++++++++++ 3 files changed, 203 insertions(+), 269 deletions(-) delete mode 100644 examples/hCaptcha/hcaptcha.py delete mode 100644 examples/hCaptcha/hcaptcha_proxy.py create mode 100644 examples/keycaptcha/keycaptcha.py diff --git a/examples/hCaptcha/hcaptcha.py b/examples/hCaptcha/hcaptcha.py deleted file mode 100644 index 9544df4..0000000 --- a/examples/hCaptcha/hcaptcha.py +++ /dev/null @@ -1,130 +0,0 @@ -from selenium import webdriver -from selenium.webdriver.common.by import By -from selenium.webdriver.support.wait import WebDriverWait -from selenium.webdriver.support import expected_conditions as EC -from urllib.parse import urlparse, parse_qs -import os -from twocaptcha import TwoCaptcha - - -# CONFIGURATION - -url = "https://2captcha.com/demo/hcaptcha" -apikey = os.getenv('APIKEY_2CAPTCHA') - - -# LOCATORS - -iframe_locator = "//div[@class='h-captcha']//iframe" -submit_button_captcha_locator = "//button[@type='submit']" -success_message_locator = "//p[contains(@class,'successMessage')]" - - -# GETTERS - -def get_element(locator): - """Waits for an element to be clickable and returns it""" - return WebDriverWait(browser, 30).until(EC.element_to_be_clickable((By.XPATH, locator))) - - -# ACTIONS - -def get_sitekey(locator): - """ - Extracts the sitekey from the iframe's URL. - - Args: - locator (str): The XPath locator of the iframe element. - Returns: - str: The sitekey value. - """ - iframe_element = get_element(locator) - url = iframe_element.get_attribute('src') - parsed_url = urlparse(url) - params = parse_qs(parsed_url.fragment) - sitekey = params.get('sitekey', [None])[0] - print(f"Sitekey received: {sitekey}") - return sitekey - -def solver_captcha(apikey, sitekey, url): - """ - Solves the hCaptcha using the 2Captcha service. - - Args: - apikey (str): The 2Captcha API key. - sitekey (str): The sitekey for the captcha. - url (str): The URL where the captcha is located. - Returns: - str: The solved captcha code, or None if an error occurred. - """ - solver = TwoCaptcha(apikey) - try: - result = solver.hcaptcha(sitekey=sitekey, url=url) - print(f"Captcha solved") - return result['code'] - except Exception as e: - print(f"An error occurred: {e}") - return None - -def send_token(captcha_token): - """ - Sends the captcha token to the hCaptcha iframe and response field. - - Args: - captcha_token (str): The solved captcha token. - """ - script = f""" - document.querySelector('iframe[src*=\\"hcaptcha\\"]').setAttribute('data-hcaptcha-response', '{captcha_token}'); - document.querySelector('[name="h-captcha-response"]').innerText = '{captcha_token}'; - """ - browser.execute_script(script) - print("Token sent") - -def click_check_button(locator): - """ - Clicks the captcha check button. - - Args: - locator (str): The XPath locator of the check button. - """ - get_element(locator).click() - print("Pressed the Check button") - -def final_message(locator): - """ - Retrieves and prints the final success message. - - Args: - locator (str): The XPath locator of the success message. - """ - message = get_element(locator).text - print(message) - - -# MAIN LOGIC - -# Automatically closes the browser after block execution completes -with webdriver.Chrome() as browser: - # Go to the specified URL - browser.get(url) - print("Started") - - # Getting sitekey from iframe - sitekey = get_sitekey(iframe_locator) - # Solving the captcha and receiving a token - token = solver_captcha(apikey, sitekey, url) - - if token: - # Sending solved captcha token - send_token(token) - # Pressing the Check button - click_check_button(submit_button_captcha_locator) - # Receiving and displaying a success message - final_message(success_message_locator) - - browser.implicitly_wait(5) - print("Finished") - else: - print("Failed to solve captcha") - - diff --git a/examples/hCaptcha/hcaptcha_proxy.py b/examples/hCaptcha/hcaptcha_proxy.py deleted file mode 100644 index 4eab99e..0000000 --- a/examples/hCaptcha/hcaptcha_proxy.py +++ /dev/null @@ -1,139 +0,0 @@ -from selenium import webdriver -from selenium.webdriver.common.by import By -from selenium.webdriver.support.wait import WebDriverWait -from selenium.webdriver.chrome.options import Options -from selenium.webdriver.support import expected_conditions as EC -from urllib.parse import urlparse, parse_qs -from webdriver_manager.chrome import ChromeDriverManager -from selenium.webdriver.chrome.service import Service -import os -from twocaptcha import TwoCaptcha -from utilities.proxy_extension import proxies - - -# CONFIGURATION - -url = 'https://2captcha.com/demo/hcaptcha' -apikey = os.getenv('APIKEY_2CAPTCHA') -proxy = {'type': 'HTTP', - 'uri': 'username:password@ip:port'} - - -# LOCATORS - -iframe_locator = "//div[@class='h-captcha']//iframe" -submit_button_captcha_locator = "//button[@type='submit']" -success_message_locator = "//p[contains(@class,'successMessage')]" - - -# GETTERS - -def get_element(locator): - """Waits for an element to be clickable and returns it""" - return WebDriverWait(browser, 30).until(EC.element_to_be_clickable((By.XPATH, locator))) - - -# ACTIONS - -def parse_proxy_uri(proxy): - """ - Parses the proxy URI to extract the scheme, login, password, IP, and port. - - Args: - proxy (dict): Dictionary containing the proxy type and URI. - Returns: - tuple: A tuple containing scheme, login, password, IP, and port. - """ - scheme = proxy['type'].lower - auth, address = proxy['uri'].split('@') - login, password = auth.split(':') - ip, port = address.split(':') - return scheme, login, password, ip, port - -def setup_proxy(proxy): - """ - Sets up the proxy configuration for Chrome browser. - - Args: - proxy (dict): Dictionary containing the proxy type and URI. - - Returns: - Options: Configured Chrome options with proxy settings. - """ - chrome_options = webdriver.ChromeOptions() - scheme, username, password, ip, port = parse_proxy_uri(proxy) - proxies_extension = proxies(scheme, username, password, ip, port) - chrome_options.add_extension(proxies_extension) - return chrome_options - -def get_sitekey(locator): - """Extracts the sitekey from the iframe's URL""" - iframe_element = get_element(locator) - url = iframe_element.get_attribute('src') - parsed_url = urlparse(url) - params = parse_qs(parsed_url.fragment) - sitekey = params.get('sitekey', [None])[0] - print(f"Sitekey received: {sitekey}") - return sitekey - -def solver_captcha(apikey, sitekey, url, proxy): - """Solves the hCaptcha using the 2Captcha service""" - solver = TwoCaptcha(apikey) - try: - result = solver.hcaptcha(sitekey=sitekey, url=url, proxy=proxy) - print(f"Captcha solved") - return result['code'] - except Exception as e: - print(f"An error occurred: {e}") - return None - -def send_token(captcha_token): - """Sends the captcha token to the hCaptcha iframe and response field""" - script = f""" - document.querySelector('iframe[src*=\\"hcaptcha\\"]').setAttribute('data-hcaptcha-response', '{captcha_token}'); - document.querySelector('[name="h-captcha-response"]').innerText = '{captcha_token}'; - """ - browser.execute_script(script) - print("Token sent") - -def click_check_button(locator): - """Clicks the captcha check button""" - get_element(locator).click() - print("Pressed the Check button") - -def final_message(locator): - """Retrieves and prints the final success message""" - message = get_element(locator).text - print(message) - - -# MAIN LOGIC - -# Configure Chrome options with proxy settings -chrome_options = setup_proxy(proxy) - -# Automatically closes the browser after block execution completes -with webdriver.Chrome(service=Service(ChromeDriverManager().install()), options=chrome_options) as browser: - # Go to the specified URL - browser.get(url) - print("Started") - - # Getting sitekey from iframe - sitekey = get_sitekey(iframe_locator) - # Solving the captcha and receiving a token - token = solver_captcha(apikey, sitekey, url, proxy) - - if token: - # Sending solved captcha token - send_token(token) - # Pressing the Check button - click_check_button(submit_button_captcha_locator) - # Receiving and displaying a success message - final_message(success_message_locator) - - browser.implicitly_wait(5) - print("Finished") - else: - print("Failed to solve captcha") - - diff --git a/examples/keycaptcha/keycaptcha.py b/examples/keycaptcha/keycaptcha.py new file mode 100644 index 0000000..28c1a16 --- /dev/null +++ b/examples/keycaptcha/keycaptcha.py @@ -0,0 +1,203 @@ +import time + +from selenium import webdriver +from selenium.webdriver.common.by import By +from selenium.webdriver.support.wait import WebDriverWait +from selenium.webdriver.support import expected_conditions as EC +import os +from twocaptcha import TwoCaptcha + + +# CONFIGURATION + +url = "https://2captcha.com/demo/keycaptcha" +apikey = os.getenv('APIKEY_2CAPTCHA') + + +# LOCATORS + +iframe_captcha = "//iframe[@name='key-captcha-widget']" +submit_button_captcha_locator = "//button[@type='submit']" +success_message_locator = "//p[contains(@class,'successMessage')]" +captcha_script_for_removal = "https://backs.keycaptcha.com/swfs/cap.js" +captcha_div_for_removal = "//div[@id='div_for_keycaptcha']" + + +# GETTERS + +def get_element(locator): + """Waits for an element to be clickable and returns it""" + return WebDriverWait(browser, 15).until(EC.element_to_be_clickable((By.XPATH, locator))) + + +# ACTIONS + +def switch_to_element(locator): + """Switches to the iframe by locator""" + element = get_element(locator) + browser.switch_to.frame(element) + +def get_captcha_parameters(): + """Executes JavaScript to extract captcha variables""" + variables = browser.execute_script( + """ + return [ + window.s_s_c_user_id, + window.s_s_c_session_id, + window.s_s_c_web_server_sign, + window.s_s_c_web_server_sign2 + ]; + """ + ) + return variables + +def solver_captcha(apikey, + s_s_c_user_id, + s_s_c_session_id, + s_s_c_web_server_sign, + s_s_c_web_server_sign2, + url): + """ + Solves the Claudflare Turnstile using the 2Captcha service. + + Args: + apikey (str): The 2Captcha API key. + sitekey (str): The sitekey for the captcha. + url (str): The URL where the captcha is located. + Returns: + str: The solved captcha code. + """ + solver = TwoCaptcha(apikey) + try: + result = solver.keycaptcha(s_s_c_user_id=s_s_c_user_id, + s_s_c_session_id=s_s_c_session_id, + s_s_c_web_server_sign=s_s_c_web_server_sign, + s_s_c_web_server_sign2=s_s_c_web_server_sign2, + url=url) + print(f"Captcha solved") + return result['code'] + except Exception as e: + print(f"An error occurred: {e}") + return None + +def token_usage(captcha_token): + """ + Use the captcha token to the hidden input field. + + Args: + captcha_token (str): The solved captcha token. + """ + script = f""" + var element = document.querySelector("input[name='capcode']"); + if (element) {{ + element.value = "{captcha_token}"; + }} + """ + browser.execute_script(script) + print("Token sent") + +def click_check_button(locator): + """ + Clicks the captcha check button. + + Args: + locator (str): The XPath locator of the check button. + """ + get_element(locator).click() + print("Pressed the Check button") + +def final_message(locator): + """ + Retrieves and prints the final success message. + + Args: + locator (str): The XPath locator of the success message. + """ + message = get_element(locator).text + print(message) + +def remove_element(identifier, by="xpath"): + """ + Removes an HTML element from the page. + + Args: + identifier (str): The identifier of the element to be removed. + - If `by="xpath"`, this should be the XPath of the element. + - If `by="src"`, this should be the `src` of a