Search code examples
pythonplaywrightplaywright-python

playwright force useragent for headless mode


How can I force the useragent in playwright python?

https://playwright.dev/python/docs/emulation#user-agent

def run(playwright):
    """ config for browser """
    browser = playwright.chromium.launch(channel='msedge', headless=False)
    context = browser.new_context(
        user_agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36 Edg/116.0.1938.81"
    )
    return browser


with sync_playwright() as p:
    browser = run(p)
    # some info
    log.info(f"name:{browser.browser_type.name}, exe_path:{browser.browser_type.executable_path}, version:{browser.version}")
    page = browser.new_page()
    log.info(f"useragent:{page.evaluate('navigator.userAgent')}")
    page.goto(dat['url'])
    :

but useragent in headlessmode is always: useragent:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) HeadlessChrome/116.0.1938.81 Safari/537.36 HeadlessEdg/116.0.1938.81


Solution

  • new_page() needs to be called on the context you've created with the user agent, not the browser:

    from playwright.sync_api import sync_playwright
    
    ua = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36 Edg/116.0.1938.81"
    
    with sync_playwright() as p:
        browser = p.chromium.launch()
        page = browser.new_page()
        context = browser.new_context(user_agent=ua)
        page = context.new_page()
        assert page.evaluate("navigator.userAgent") == ua
    

    If you really want to use run(), you can:

    def run(playwright):
        # ...
        return context, browser
    
    with sync_playwright() as p:
        context, browser = run(p)
        page = context.new_page()
        # ...