python版本的 playwright , 如何拦截请求,替换响应内容
from playwright.sync_api import Playwright, sync_playwright
def request_interceptor(route, request): logger.info(request.url) if 'api.js' in request.url: # 替换响应内容 route.fulfill( status=200, body=js_content, headers={ 'Access-Control-Allow-Origin': '*', 'content-type': 'application/javascript; charset=UTF-8'} ) else: # 继续原始请求 route.continue_()
with sync_playwright() as p: browser = p.firefox.launch(headless=False, timeout=12000) page = browser.new_page() page.route('**/*', request_interceptor)
page.goto('http://example.com')