Compare commits
4 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 5783feb60d | |||
| 98ef180878 | |||
| 6b7e856e38 | |||
| ccb8479242 |
43
PROJECT_SUMMARY.md
Normal file
43
PROJECT_SUMMARY.md
Normal file
@@ -0,0 +1,43 @@
|
||||
# Web Capture API 项目
|
||||
|
||||
## 待推送信息
|
||||
|
||||
- **仓库地址**: http://121.40.164.32:12007/hz4th_coder/web-capture-api.git
|
||||
- **当前版本**: v1.0.2
|
||||
- **提交历史**:
|
||||
- v1.0.0: 初始化项目
|
||||
- v1.0.1: 修改端口为 16025
|
||||
- v1.0.2: 修复 agent-browser socket 权限问题
|
||||
|
||||
## 操作步骤
|
||||
|
||||
### 1. 在 Git 平台创建仓库
|
||||
|
||||
请大爷登录 Git 平台 (http://121.40.164.32:12007) 并创建仓库:
|
||||
- 仓库名称: `web-capture-api`
|
||||
- 所属用户: `hz4th_coder`
|
||||
- 可见性: 公开或私有(根据需要)
|
||||
|
||||
### 2. 推送代码
|
||||
|
||||
仓库创建后,运行以下命令:
|
||||
|
||||
```bash
|
||||
cd /home/openclaw/.openclaw/workspace-hz4th_coder/works/web-capture-api
|
||||
git push -u origin master --tags
|
||||
```
|
||||
|
||||
## 项目功能
|
||||
|
||||
- 网页截图(全页或视口)
|
||||
- HTML 代码提取
|
||||
- 自动滚动加载动态内容
|
||||
- 自定义视口大小
|
||||
- Web 界面和 RESTful API
|
||||
- 支持 agent-browser 和 Playwright 双后端
|
||||
- Docker 部署支持
|
||||
|
||||
## 服务地址
|
||||
|
||||
- Web 界面: http://192.168.0.101:16025
|
||||
- API 接口: http://192.168.0.101:16025/api/capture
|
||||
124
app.py
124
app.py
@@ -20,8 +20,17 @@ from datetime import datetime
|
||||
try:
|
||||
from playwright.async_api import async_playwright
|
||||
PLAYWRIGHT_AVAILABLE = True
|
||||
# 尝试导入 stealth 反检测
|
||||
try:
|
||||
from playwright_stealth import stealth_async
|
||||
STEALTH_AVAILABLE = True
|
||||
except ImportError:
|
||||
STEALTH_AVAILABLE = False
|
||||
print("⚠️ playwright-stealth 未安装,反爬虫能力降低")
|
||||
except ImportError:
|
||||
PLAYWRIGHT_AVAILABLE = False
|
||||
STEALTH_AVAILABLE = False
|
||||
print("⚠️ Playwright 未安装,请运行: pip install playwright && playwright install chromium")
|
||||
|
||||
# 检查 agent-browser 是否可用
|
||||
def check_agent_browser():
|
||||
@@ -44,6 +53,10 @@ CORS(app)
|
||||
CAPTURE_DIR = Path(tempfile.gettempdir()) / "web_captures"
|
||||
CAPTURE_DIR.mkdir(exist_ok=True)
|
||||
|
||||
# agent-browser socket 目录
|
||||
os.environ.setdefault("AGENT_BROWSER_SOCKET_DIR", "/tmp/agent-browser-sockets")
|
||||
Path(os.environ["AGENT_BROWSER_SOCKET_DIR"]).mkdir(exist_ok=True, parents=True)
|
||||
|
||||
|
||||
class AgentBrowserSession:
|
||||
"""agent-browser 会话管理器"""
|
||||
@@ -55,12 +68,17 @@ class AgentBrowserSession:
|
||||
def run(self, cmd, timeout=60000):
|
||||
"""执行 agent-browser 命令"""
|
||||
full_cmd = self.base_cmd + cmd
|
||||
# 设置必要的环境变量
|
||||
env = os.environ.copy()
|
||||
env['AGENT_BROWSER_SOCKET_DIR'] = '/tmp/agent-browser-sockets'
|
||||
env['AGENT_BROWSER_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'
|
||||
try:
|
||||
result = subprocess.run(
|
||||
full_cmd,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=timeout / 1000
|
||||
timeout=timeout / 1000,
|
||||
env=env
|
||||
)
|
||||
return result.returncode == 0, result.stdout, result.stderr
|
||||
except subprocess.TimeoutExpired:
|
||||
@@ -70,6 +88,9 @@ class AgentBrowserSession:
|
||||
|
||||
def open(self, url):
|
||||
"""打开网页"""
|
||||
# 添加反爬虫检测的 User-Agent
|
||||
env = os.environ.copy()
|
||||
env['AGENT_BROWSER_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'
|
||||
return self.run(["open", url], timeout=30000)
|
||||
|
||||
def set_viewport(self, width, height):
|
||||
@@ -130,6 +151,9 @@ def capture_with_agent_browser(
|
||||
# 打开网页
|
||||
success, stdout, stderr = session.open(url)
|
||||
if not success:
|
||||
# 检查是否是反爬虫拦截
|
||||
if "403" in stdout or "Access Denied" in stdout:
|
||||
return {"success": False, "error": "网站反爬虫拦截 (403),建议使用 Playwright 后端或手动添加请求头"}
|
||||
return {"success": False, "error": f"Failed to open URL: {stderr}"}
|
||||
|
||||
# 等待页面加载
|
||||
@@ -179,28 +203,120 @@ async def capture_with_playwright(
|
||||
):
|
||||
"""
|
||||
使用 Playwright 捕获网页
|
||||
Playwright 有更强的反爬虫能力
|
||||
"""
|
||||
if not PLAYWRIGHT_AVAILABLE:
|
||||
return {"success": False, "error": "Playwright not installed"}
|
||||
return {"success": False, "error": "Playwright not installed. Run: pip install playwright && playwright install chromium"}
|
||||
|
||||
session_id = str(uuid.uuid4())[:8]
|
||||
|
||||
try:
|
||||
async with async_playwright() as p:
|
||||
browser = await p.chromium.launch(headless=True)
|
||||
# 启动浏览器,添加反检测配置
|
||||
# 尝试使用真实 Chrome(如果安装了)
|
||||
try:
|
||||
# 首先尝试使用真实 Chrome 浏览器
|
||||
browser = await p.chromium.launch(
|
||||
headless=True,
|
||||
channel='chrome', # 使用真实 Chrome 而不是 Chromium
|
||||
args=[
|
||||
'--disable-blink-features=AutomationControlled',
|
||||
'--disable-dev-shm-usage',
|
||||
'--no-sandbox',
|
||||
'--ignore-certificate-errors',
|
||||
]
|
||||
)
|
||||
except:
|
||||
# 如果没有 Chrome,使用 Chromium
|
||||
browser = await p.chromium.launch(
|
||||
headless=True,
|
||||
args=[
|
||||
'--disable-blink-features=AutomationControlled',
|
||||
'--disable-dev-shm-usage',
|
||||
'--no-sandbox',
|
||||
'--ignore-certificate-errors',
|
||||
]
|
||||
)
|
||||
|
||||
viewport_settings = viewport or {"width": 1920, "height": 1080}
|
||||
|
||||
# 创建上下文,模拟真实浏览器
|
||||
context = await browser.new_context(
|
||||
viewport={
|
||||
"width": viewport_settings.get("width", 1920),
|
||||
"height": viewport_settings.get("height", 1080)
|
||||
},
|
||||
user_agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
|
||||
user_agent='Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.6099.109 Safari/537.36',
|
||||
# 添加更多浏览器特征
|
||||
locale='en-US',
|
||||
timezone_id='America/New_York',
|
||||
color_scheme='light',
|
||||
has_touch=False,
|
||||
is_mobile=False,
|
||||
java_script_enabled=True,
|
||||
accept_downloads=True,
|
||||
)
|
||||
|
||||
# 注入反检测脚本
|
||||
await context.add_init_script("""
|
||||
// 移除 webdriver 标记
|
||||
Object.defineProperty(navigator, 'webdriver', {
|
||||
get: () => undefined
|
||||
});
|
||||
|
||||
// 添加插件
|
||||
Object.defineProperty(navigator, 'plugins', {
|
||||
get: () => {
|
||||
return [
|
||||
{name: 'Chrome PDF Plugin', filename: 'internal-pdf-viewer', description: 'Portable Document Format'},
|
||||
{name: 'Chrome PDF Viewer', filename: 'mhjfbmdgncjokjjpdkfnmlglggk', description: ''},
|
||||
{name: 'Native Client', filename: 'internal-nacl-plugin', description: ''}
|
||||
];
|
||||
}
|
||||
});
|
||||
|
||||
// 语言列表
|
||||
Object.defineProperty(navigator, 'languages', {
|
||||
get: () => ['en-US', 'en', 'zh-CN']
|
||||
});
|
||||
|
||||
// 平台
|
||||
Object.defineProperty(navigator, 'platform', {
|
||||
get: () => 'Win32'
|
||||
});
|
||||
|
||||
// 硬件并发
|
||||
Object.defineProperty(navigator, 'hardwareConcurrency', {
|
||||
get: () => 8
|
||||
});
|
||||
|
||||
// 设备内存
|
||||
Object.defineProperty(navigator, 'deviceMemory', {
|
||||
get: () => 8
|
||||
});
|
||||
|
||||
// Chrome 对象
|
||||
window.chrome = {
|
||||
runtime: {
|
||||
PlatformOs: {MAC: 'mac', WIN: 'win', ANDROID: 'android', CROS: 'cros', LINUX: 'linux', OPENBSD: 'openbsd'},
|
||||
PlatformArch: {ARM: 'arm', X86_32: 'x86-32', X86_64: 'x86-64'},
|
||||
PlatformNaclArch: {ARM: 'arm', X86_32: 'x86-32', X86_64: 'x86-64'},
|
||||
Request: function() {},
|
||||
connect: function() {},
|
||||
sendMessage: function() {}
|
||||
},
|
||||
loadTimes: function() {},
|
||||
csi: function() {},
|
||||
app: {}
|
||||
};
|
||||
""")
|
||||
|
||||
page = await context.new_page()
|
||||
|
||||
# 应用 stealth 反检测(如果可用)
|
||||
if STEALTH_AVAILABLE:
|
||||
await stealth_async(page)
|
||||
|
||||
try:
|
||||
await page.goto(url, wait_until="networkidle", timeout=30000)
|
||||
except:
|
||||
|
||||
@@ -405,7 +405,7 @@
|
||||
submitBtn.disabled = true;
|
||||
|
||||
try {
|
||||
const response = await fetch('http://localhost:16025/api/capture', {
|
||||
const response = await fetch('/api/capture', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json'
|
||||
|
||||
Reference in New Issue
Block a user