好久没更了,水篇文章,通过dp提供的cdp接口执行cdp命令,替换指定请求的响应。

from DrissionPage import ChromiumPage, ChromiumOptions
import time
import base64

def intercept_requests(page: ChromiumPage, target_js_url, custom_js_code):
    """
    启用请求拦截,替换指定的JS请求的响应体为自定义代码
    :param target_js_url: 需要拦截并替换的JS文件的URL
    :param custom_js_code: 自定义JS代码
    """
    # 启用网络监控和请求拦截
    page.run_cdp('Network.enable')
    page.run_cdp('Fetch.enable', patterns=[{
        'urlPattern': target_js_url
    }])
    # 处理请求拦截
    def on_request_paused(**params):
        request = params.get('request')
        interception_id = params.get('interceptionId')
        if request and target_js_url in request['url']:
            print(f"Intercepted Request: {request['url']}")
            print(f"Replacing {target_js_url} with custom JS")
            modified_js = custom_js_code
            encoded_js = base64.b64encode(modified_js.encode('utf-8')).decode('utf-8')
            page.run_cdp('Fetch.fulfillRequest',
                         requestId=params['requestId'],
                         responseCode=200,
                         responseHeaders=[{
                             'name': 'Content-Type',
                             'value': 'application/javascript'
                         }],
                         body=encoded_js)
        else:
            page.run_cdp('Fetch.continueRequest', interceptionId=interception_id)

    # 设置回调,处理请求拦截
    page._driver.set_callback('Fetch.requestPaused', on_request_paused, immediate=True)
    print("Request interception has been set up.")

chrome_path = r'C:\Program Files\Google\Chrome\Application\chrome.exe'

option = ChromiumOptions()
option.set_browser_path(chrome_path)
page = ChromiumPage(addr_or_opts=option)
page.clear_cache()

with open(r'fireyejs.js', 'r', encoding="UTF-8") as f:
    custom_js_code = f.read()

intercept_requests(page, "https://g.xxxxxx.com/AWSC/fireyejs/1.231.13/fireyejs.js", custom_js_code)
page.get('https://login.xxxxxx.com')
time.sleep(999)