1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
| import asyncio import json import websockets
class CDPMobileEmulator: """CDP 移动设备模拟器""" DEVICES = { "iphone_14_pro": (390, 844, 3, True, 1170, 2532), "iphone_se": (375, 667, 2, True, 750, 1334), "pixel_7": (412, 915, 2.625, True, 1080, 2400), "galaxy_s22": (360, 780, 3, True, 1080, 2340), "ipad_pro": (1024, 1366, 2, True, 2048, 2732), } USER_AGENTS = { "iphone_14_pro": ("Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X) " "AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148"), "pixel_7": ("Mozilla/5.0 (Linux; Android 14; Pixel 7) " "AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.6099.144 Mobile"), } def __init__(self, ws, session_id): self.ws = ws self.session_id = session_id self._cmd_id = 0 async def _cmd(self, method, params=None): self._cmd_id += 1 msg = { "sessionId": self.session_id, "id": self._cmd_id, "method": method, "params": params or {} } await self.ws.send(json.dumps(msg)) async for resp in self.ws: data = json.loads(resp) if data.get("id") == self._cmd_id: return data.get("result", {}) async def emulate(self, device_name): if device_name not in self.DEVICES: raise ValueError(f"Unknown device: {device_name}") w, h, scale, mobile, sw, sh = self.DEVICES[device_name] await self._cmd("Emulation.setDeviceMetricsOverride", { "width": w, "height": h, "deviceScaleFactor": scale, "mobile": mobile, "screenWidth": sw, "screenHeight": sh }) if device_name in self.USER_AGENTS: await self._cmd("Emulation.setUserAgentOverride", { "userAgent": self.USER_AGENTS[device_name] }) print(f"Emulated: {device_name}") async def set_geo(self, lat, lng, accuracy=100): await self._cmd("Emulation.setGeolocationOverride", { "latitude": lat, "longitude": lng, "accuracy": accuracy }) async def set_orientation(self, alpha=0, beta=0, gamma=0): await self._cmd("Emulation.setDeviceOrientationOverride", { "alpha": alpha, "beta": beta, "gamma": gamma }) async def reset(self): await self._cmd("Emulation.clearDeviceMetricsOverride") await self._cmd("Emulation.setUserAgentOverride", {"userAgent": ""}) await self._cmd("Emulation.clearGeolocationOverride") await self._cmd("Emulation.clearDeviceOrientationOverride")
|