python控制chrome例子---网页截图

发布时间:2026/8/30 5:01:40
python控制chrome例子---网页截图 PyChrome 允许 Python 脚本通过 Chrome DevTools Protocol (CDP) 控制 Chrome 浏览器。使用前需确保 Chrome 以远程调试模式启动。‌前置准备在终端启动 Chrome无头模式推荐用于服务器google-chrome --headless --disable-gpu --remote-debugging-port9222# Linuxgoogle-chrome --headlessnew --disable-gpu --remote-debugging-port9222# Windows# C:\Program Files\Google\Chrome Dev\Application\chrome.exe# chrome.exe --headlessnew --remote-debugging-port9222start chrome chrome.exe --headlessnew --remote-debugging-port9222python文件:basic_automation.py basic_automation_v1.py(完善后的升级版)import pychrome import time import os def basic_automation_example(): 基础示例打开网页并截图 # 1. 创建浏览器实例连接到本地调试端口 browser pychrome.Browser(urlhttp://127.0.0.1:9222) try: # 2. 新建一个标签页 tab browser.new_tab() # 3. 注册事件回调(可选用于调试) def request_will_be_sent(**kwargs): url kwargs.get(request, {}).get(url, ) print(f正在加载资源: {url[:50]}...) tab.Network.requestWillBeSent request_will_be_sent # 4. 启动标签页并启用网络域 tab.start() tab.Network.enable() # 5. 导航到目标网页 # target_url https://www.python.org/ target_url https://www.baidu.com print(f正在导航至: {target_url}) tab.Page.navigate(urltarget_url, _timeout15) # 6. 等待页面加载完成 # tab.wait(5) # 使用sleep代替不会阻塞websocket接收线程 time.sleep(5) # 7. 截取屏幕截图 screenshot_path screenshot.png print(f正在保存截图至: {screenshot_path}) # captureScreenshot 返回 base64 编码的图片数据 result tab.Page.captureScreenshot() if result: import base64 image_data base64.b64decode(result[data]) with open(screenshot_path, wb) as f: f.write(image_data) print(截图保存成功) # 8. 停止标签页并关闭 tab.stop() browser.close_tab(tab) # browser.quit() except Exception as e: print(f发生错误: {e}) finally: # 确保浏览器连接关闭 try: browser.close() except: pass if __name__ __main__: basic_automation_example()