capturing capcha tokens
This commit is contained in:
@ -438,6 +438,16 @@ class MEXCRequestInterceptor:
|
|||||||
if self.session_cookies:
|
if self.session_cookies:
|
||||||
print(f" 🍪 Cookies: {self.cookies_file}")
|
print(f" 🍪 Cookies: {self.cookies_file}")
|
||||||
|
|
||||||
|
# Extract and save CAPTCHA tokens from captured requests
|
||||||
|
captcha_tokens = self.extract_captcha_tokens()
|
||||||
|
if captcha_tokens:
|
||||||
|
captcha_file = f"mexc_captcha_tokens_{self.timestamp}.json"
|
||||||
|
with open(captcha_file, 'w') as f:
|
||||||
|
json.dump(captcha_tokens, f, indent=2)
|
||||||
|
logger.info(f"Saved CAPTCHA tokens to {captcha_file}")
|
||||||
|
else:
|
||||||
|
logger.warning("No CAPTCHA tokens found in captured requests")
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(f"❌ Error saving data: {e}")
|
print(f"❌ Error saving data: {e}")
|
||||||
|
|
||||||
@ -488,6 +498,28 @@ class MEXCRequestInterceptor:
|
|||||||
self._save_all_data()
|
self._save_all_data()
|
||||||
logger.info("Final data save complete")
|
logger.info("Final data save complete")
|
||||||
|
|
||||||
|
def extract_captcha_tokens(self):
|
||||||
|
"""Extract CAPTCHA tokens from captured requests"""
|
||||||
|
captcha_tokens = []
|
||||||
|
for request in self.captured_requests:
|
||||||
|
if 'captcha-token' in request.get('headers', {}):
|
||||||
|
token = request['headers']['captcha-token']
|
||||||
|
captcha_tokens.append({
|
||||||
|
'token': token,
|
||||||
|
'url': request.get('url', ''),
|
||||||
|
'timestamp': request.get('timestamp', '')
|
||||||
|
})
|
||||||
|
elif 'captcha' in request.get('url', '').lower():
|
||||||
|
response = request.get('response', {})
|
||||||
|
if response and 'captcha-token' in response.get('headers', {}):
|
||||||
|
token = response['headers']['captcha-token']
|
||||||
|
captcha_tokens.append({
|
||||||
|
'token': token,
|
||||||
|
'url': request.get('url', ''),
|
||||||
|
'timestamp': request.get('timestamp', '')
|
||||||
|
})
|
||||||
|
return captcha_tokens
|
||||||
|
|
||||||
def main():
|
def main():
|
||||||
"""Main function to run the interceptor"""
|
"""Main function to run the interceptor"""
|
||||||
print("🚀 MEXC Request Interceptor with ChromeDriver")
|
print("🚀 MEXC Request Interceptor with ChromeDriver")
|
||||||
|
@ -19,6 +19,8 @@ from typing import Dict, List, Optional, Any
|
|||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
import uuid
|
import uuid
|
||||||
from urllib.parse import urlencode
|
from urllib.parse import urlencode
|
||||||
|
import glob
|
||||||
|
import os
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
@ -191,16 +193,30 @@ class MEXCFuturesWebClient:
|
|||||||
def _extract_captcha_token_from_browser(self) -> str:
|
def _extract_captcha_token_from_browser(self) -> str:
|
||||||
"""
|
"""
|
||||||
Extract captcha token from browser session using stored cookies or requests.
|
Extract captcha token from browser session using stored cookies or requests.
|
||||||
This is a placeholder for actual implementation which would interact with browser data.
|
This method looks for the most recent mexc_captcha_tokens JSON file to retrieve a token.
|
||||||
"""
|
"""
|
||||||
try:
|
try:
|
||||||
# Placeholder for extracting token from browser session or stored data
|
# Look for the most recent mexc_captcha_tokens file
|
||||||
# In a real scenario, this would parse the mexc_requests JSON file or interact with Selenium
|
captcha_files = glob.glob("mexc_captcha_tokens_*.json")
|
||||||
logger.info("MEXC: Attempting to extract captcha token from browser data")
|
if not captcha_files:
|
||||||
# For now, return empty string as placeholder
|
logger.error("MEXC: No CAPTCHA token files found")
|
||||||
return ""
|
return ""
|
||||||
|
|
||||||
|
# Sort files by timestamp (most recent first)
|
||||||
|
latest_file = max(captcha_files, key=os.path.getctime)
|
||||||
|
logger.info(f"MEXC: Using CAPTCHA token file {latest_file}")
|
||||||
|
|
||||||
|
with open(latest_file, 'r') as f:
|
||||||
|
captcha_data = json.load(f)
|
||||||
|
|
||||||
|
if captcha_data and isinstance(captcha_data, list) and len(captcha_data) > 0:
|
||||||
|
# Return the most recent token
|
||||||
|
return captcha_data[0].get('token', '')
|
||||||
|
else:
|
||||||
|
logger.error("MEXC: No valid CAPTCHA tokens found in file")
|
||||||
|
return ""
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f"MEXC: Error extracting captcha token from browser: {str(e)}")
|
logger.error(f"MEXC: Error extracting captcha token from browser data: {str(e)}")
|
||||||
return ""
|
return ""
|
||||||
|
|
||||||
def generate_signature(self, method: str, path: str, params: Dict[str, Any],
|
def generate_signature(self, method: str, path: str, params: Dict[str, Any],
|
||||||
|
45
docs/MEXC_CAPTCHA_HANDLING.md
Normal file
45
docs/MEXC_CAPTCHA_HANDLING.md
Normal file
@ -0,0 +1,45 @@
|
|||||||
|
# MEXC CAPTCHA Handling Documentation
|
||||||
|
|
||||||
|
## Overview
|
||||||
|
This document outlines the mechanism implemented in the `gogo2` trading dashboard project to handle CAPTCHA challenges encountered during automated trading on the MEXC platform. The goal is to enable seamless trading operations without manual intervention by capturing and integrating CAPTCHA tokens.
|
||||||
|
|
||||||
|
## CAPTCHA Handling Mechanism
|
||||||
|
|
||||||
|
### 1. Browser Automation with `MEXCBrowserAutomation`
|
||||||
|
- The `MEXCBrowserAutomation` class in `core/mexc_webclient/auto_browser.py` is responsible for launching a browser session using Selenium WebDriver.
|
||||||
|
- It navigates to the MEXC futures trading page and captures HTTP requests and responses, including those related to CAPTCHA challenges.
|
||||||
|
- When a CAPTCHA request is detected (e.g., requests to `gcaptcha4.geetest.com` or specific MEXC CAPTCHA endpoints), the relevant token is extracted from the request headers or response data.
|
||||||
|
- These tokens are saved to JSON files named `mexc_captcha_tokens_YYYYMMDD_HHMMSS.json` in the project root directory for later use.
|
||||||
|
|
||||||
|
### 2. Integration with `MEXCFuturesWebClient`
|
||||||
|
- The `MEXCFuturesWebClient` class in `core/mexc_webclient/mexc_futures_client.py` is updated to handle CAPTCHA challenges during API requests.
|
||||||
|
- A `MEXCSessionManager` class manages session data, including cookies and CAPTCHA tokens, by reading the latest token from the saved JSON files.
|
||||||
|
- When a request fails due to a CAPTCHA challenge, the client retrieves the latest token and includes it in the request headers under `captcha-token`.
|
||||||
|
|
||||||
|
### 3. Manual Testing and Data Capture
|
||||||
|
- The script `run_mexc_browser.py` provides an interactive way to test the `MEXCFuturesWebClient` and capture CAPTCHA tokens.
|
||||||
|
- Users can run this script to perform test trades, monitor requests, and save captured data, including tokens, to files.
|
||||||
|
- The captured tokens are used in subsequent API calls to authenticate trading actions like opening or closing positions.
|
||||||
|
|
||||||
|
## Usage Instructions
|
||||||
|
|
||||||
|
### Running Browser Automation
|
||||||
|
1. Execute `python run_mexc_browser.py` to start the browser automation.
|
||||||
|
2. Choose options like 'Perform test trade (manual)' to simulate trading actions and capture CAPTCHA tokens.
|
||||||
|
3. The script saves tokens to a JSON file, which can be used by `MEXCFuturesWebClient` for automated trading.
|
||||||
|
|
||||||
|
### Automated Trading with CAPTCHA Tokens
|
||||||
|
- Ensure that the `MEXCFuturesWebClient` is configured to use the latest CAPTCHA token file. This is handled automatically by the `MEXCSessionManager` class, which looks for the most recent file matching the pattern `mexc_captcha_tokens_*.json`.
|
||||||
|
- If a CAPTCHA challenge is encountered during trading, the client will attempt to use the saved token to proceed with the request.
|
||||||
|
|
||||||
|
## Limitations and Notes
|
||||||
|
- **Token Validity**: CAPTCHA tokens have a limited validity period. If the saved token is outdated, a new browser session may be required to capture fresh tokens.
|
||||||
|
- **Automation**: Currently, token capture requires manual initiation via `run_mexc_browser.py`. Future enhancements may include background automation for continuous token updates.
|
||||||
|
- **Windows Compatibility**: All scripts and file operations are designed to work on Windows systems, adhering to project rules for compatibility.
|
||||||
|
|
||||||
|
## Troubleshooting
|
||||||
|
- If trades fail due to CAPTCHA issues, check if a recent token file exists and contains valid tokens.
|
||||||
|
- Run `run_mexc_browser.py` to capture new tokens if necessary.
|
||||||
|
- Verify that file paths and permissions are correct for reading/writing token files on Windows.
|
||||||
|
|
||||||
|
For further assistance or to report issues, refer to the project's main documentation or contact the development team.
|
12
mexc_captcha_t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ateway/captcha_api/captcha/robot/robot.future.openlong.ETH_USDT.300X",
|
||||||
|
"timestamp": "2025-07-03T02:24:51.150716"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"token": "geetest eyJsb3ROdW1iZXIiOiI5ZWVlMDQ2YTg1MmQ0MTU3YTNiYjdhM2M5MzJiNzJiYSIsImNhcHRjaGFPdXRwdXQiOiJaVkwzS3FWaWxnbEZjQWdXOENIQVgxMUVBLVVPUnE1aURQSldzcmlubDFqelBhRTNiUGlEc0VrVTJUR0xuUzRHZk9hVUhKRW1ZOS1FN0h3Q3NNV3hvbVZsNnIwZXRYZzIyWHBGdUVUdDdNS19Ud1J6NnotX2pCXzRkVDJqTnJRN0J3cExjQ25DNGZQUXQ5V040TWxrZ0NMU3p6MERNd09SeHJCZVRkVE5pSU5BdmdFRDZOMkU4a19XRmJ6SFZsYUtieElnM3dLSGVTMG9URU5DLUNaNElnMDJlS2x3UWFZY3liRnhKU2ZrWG1vekZNMDVJSHVDYUpwT0d2WXhhYS1YTWlDeGE0TnZlcVFqN2JwNk04Q09PSnNxNFlfa0pkX0Ruc2w0UW1memZCUTZseF9tenFCMnFweThxd3hKTFVYX0g3TGUyMXZ2bGtubG1KS0RSUEJtTWpUcGFiZ2F4M3Q1YzJmbHJhRjk2elhHQzVBdVVQY1FrbDIyOW0xSmlnMV83cXNfTjdpZFozd0hRcWZFZGxSYVRKQTR2U18yYnFlcGdLblJ3Y3oxaWtOOW1RaWNOSnpSNFNhdm1Pdi1BSzhwSEF0V2lkVjhrTkVYc3dGbUdSazFKQXBEX1hVUjlEdl9sNWJJNEFnbVJhcVlGdjhfRUNvN1g2cmt2UGZuOElTcCIsInBhc3NUb2tlbiI6IjRmZDFhZmU5NzI3MTk0ZGI3MDNlMDg2NWQ0ZDZjZTIyYzMwMzUyNzQ5NzVjMDIwNDFiNTY3Y2Y3MDdhYjM1OTMiLCJnZW5UaW1lIjoiMTc1MTQ5ODY5MiJ9",
|
||||||
|
"url": "https://www.mexc.com/ucgateway/captcha_api/captcha/robot/robot.future.closelong.ETH_USDT.300X",
|
||||||
|
"timestamp": "2025-07-03T02:24:57.885947"
|
||||||
|
}
|
||||||
|
]
|
8072
mexc_requests_20250703_022428.json
Normal file
8072
mexc_requests_20250703_022428.json
Normal file
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user