Files
ai_wht_wechat/backend/test_damai_proxy.py
2026-01-06 19:36:42 +08:00

208 lines
6.5 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"""
大麦固定代理IP测试脚本
测试两个固定代理IP在无头浏览器中的可用性
"""
import asyncio
import sys
from playwright.async_api import async_playwright
# 大麦固定代理IP配置
DAMAI_PROXIES = [
{
"name": "大麦代理1",
"server": "http://36.137.177.131:50001",
"username": "qqwvy0",
"password": "mun3r7xz"
},
{
"name": "大麦代理2",
"server": "http://111.132.40.72:50002",
"username": "ih3z07",
"password": "078bt7o5"
}
]
async def test_proxy(proxy_config: dict):
"""
测试单个代理IP
Args:
proxy_config: 代理配置字典
"""
print(f"\n{'='*60}")
print(f"🔍 开始测试: {proxy_config['name']}")
print(f" 代理服务器: {proxy_config['server']}")
print(f" 认证信息: {proxy_config['username']} / {proxy_config['password']}")
print(f"{'='*60}")
playwright = None
browser = None
try:
# 启动Playwright
playwright = await async_playwright().start()
print("✅ Playwright启动成功")
# 配置代理
proxy_settings = {
"server": proxy_config["server"],
"username": proxy_config["username"],
"password": proxy_config["password"]
}
# 启动浏览器(带代理)
print(f"🚀 正在启动浏览器(使用代理: {proxy_config['server']}...")
browser = await playwright.chromium.launch(
headless=True,
proxy=proxy_settings,
args=[
'--disable-blink-features=AutomationControlled',
'--no-sandbox',
'--disable-setuid-sandbox',
'--disable-dev-shm-usage',
'--disable-web-security',
'--disable-features=IsolateOrigins,site-per-process',
]
)
print("✅ 浏览器启动成功")
# 创建上下文
context = await browser.new_context(
viewport={'width': 1280, 'height': 720},
user_agent='Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36'
)
print("✅ 浏览器上下文创建成功")
# 创建页面
page = await context.new_page()
print("✅ 页面创建成功")
# 测试1: 访问IP检测网站检查代理IP是否生效
print("\n📍 测试1: 访问IP检测网站...")
try:
await page.goto("http://httpbin.org/ip", timeout=30000)
await asyncio.sleep(2)
# 获取页面内容
content = await page.content()
print("✅ 访问成功,页面内容:")
print(content[:500]) # 只显示前500字符
# 尝试提取IP信息
ip_info = await page.evaluate("() => document.body.innerText")
print(f"\n🌐 当前IP信息:\n{ip_info}")
except Exception as e:
print(f"❌ 测试1失败: {str(e)}")
# 测试2: 访问小红书登录页(检查代理在实际场景中是否可用)
print("\n📍 测试2: 访问小红书登录页...")
try:
await page.goto("https://creator.xiaohongshu.com/login", timeout=30000)
await asyncio.sleep(3)
title = await page.title()
url = page.url
print(f"✅ 访问成功")
print(f" 页面标题: {title}")
print(f" 当前URL: {url}")
except Exception as e:
print(f"❌ 测试2失败: {str(e)}")
# 测试3: 访问大麦网(测试目标网站)
print("\n📍 测试3: 访问大麦网...")
try:
await page.goto("https://www.damai.cn/", timeout=30000)
await asyncio.sleep(3)
title = await page.title()
url = page.url
print(f"✅ 访问成功")
print(f" 页面标题: {title}")
print(f" 当前URL: {url}")
except Exception as e:
print(f"❌ 测试3失败: {str(e)}")
print(f"\n{proxy_config['name']} 测试完成")
except Exception as e:
print(f"\n{proxy_config['name']} 测试失败: {str(e)}")
import traceback
traceback.print_exc()
finally:
# 清理资源
try:
if browser:
await browser.close()
print("🧹 浏览器已关闭")
if playwright:
await playwright.stop()
print("🧹 Playwright已停止")
except Exception as e:
print(f"⚠️ 清理资源时出错: {str(e)}")
async def test_all_proxies():
"""测试所有代理IP"""
print("\n" + "="*60)
print("🎯 大麦固定代理IP测试")
print("="*60)
print(f"📊 共配置 {len(DAMAI_PROXIES)} 个代理IP")
# 依次测试每个代理
for i, proxy_config in enumerate(DAMAI_PROXIES, 1):
print(f"\n\n{'#'*60}")
print(f"# 测试进度: {i}/{len(DAMAI_PROXIES)}")
print(f"{'#'*60}")
await test_proxy(proxy_config)
# 测试间隔
if i < len(DAMAI_PROXIES):
print(f"\n⏳ 等待5秒后测试下一个代理...")
await asyncio.sleep(5)
print("\n" + "="*60)
print("🎉 所有代理测试完成!")
print("="*60)
async def test_single_proxy(index: int = 0):
"""
测试单个代理IP
Args:
index: 代理索引0或1
"""
if index < 0 or index >= len(DAMAI_PROXIES):
print(f"❌ 无效的代理索引: {index},请使用 0 或 1")
return
await test_proxy(DAMAI_PROXIES[index])
if __name__ == "__main__":
# Windows环境下设置事件循环策略
if sys.platform == 'win32':
asyncio.set_event_loop_policy(asyncio.WindowsProactorEventLoopPolicy())
# 解析命令行参数
if len(sys.argv) > 1:
try:
proxy_index = int(sys.argv[1])
print(f"🎯 测试单个代理(索引: {proxy_index}")
asyncio.run(test_single_proxy(proxy_index))
except ValueError:
print("❌ 参数错误,请使用: python test_damai_proxy.py [0|1]")
print(" 0: 测试代理1")
print(" 1: 测试代理2")
print(" 不带参数: 测试所有代理")
else:
# 测试所有代理
asyncio.run(test_all_proxies())