程式語言 - Python - Selenium - Hook POST Event



參考資訊:
https://selenium-python.readthedocs.io/getting-started.html

main.py

from selenium import webdriver
import time
import json

driver = webdriver.Chrome()
driver.get("file:///tmp/main.html")

driver.execute_script("""
(function() {
    const originalFetch = window.fetch;
    window.fetch = function() {
        let args = arguments;
        
        window._fetchLog = window._fetchLog || [];
        window._fetchLog.push({
            type: 'request',
            url: args[0],
            options: args[1] ? JSON.stringify(args[1]) : null
        });
        
        let r = originalFetch.apply(this, args).then(response => {
            response.clone().text().then(text => {
                window._fetchLog.push({
                    type: 'response',
                    url: args[0],
                    body: text
                });
            });
            return response;
        });

        return arguments;
    };
})();
""")

time.sleep(60)

logs = driver.execute_script("return window._fetchLog || []")
print(json.dumps(logs, indent=2))

driver.quit()

/tmp/main.html

<!doctype html>
<html lang="en">
<body>
    <div class="wrap">
        <button id="btn" type="button">Test</button>
    </div>

    <script>
        document.getElementById('btn').addEventListener('click', () => {
            fetch('www.google.com');
        });
    </script>
</body>
</html>



執行:

$ python3 main.py 
    [
      {
        "options": null,
        "type": "request",
        "url": "www.google.com"
      }
    ]