playwright-python icon indicating copy to clipboard operation
playwright-python copied to clipboard

[Bug]: Chromium already set to headless=True but error logs still say "Looks like you launched a headed browser without having a XServer running. Set either 'headless: true' or use 'xvfb-run <your-playwright-app>'"

Open anobilisgorse opened this issue 2 years ago • 7 comments

Version

1.45.1

Steps to reproduce

This is how we use Playwright in our application

# service/html_converter.py
import subprocess
import logging
import os

import boto3
from playwright.sync_api import sync_playwright

logger = logging.getLogger()
logger.setLevel(logging.INFO)

s3 = boto3.client('s3')

DEFAULT_LOCATION = '/tmp'

# Schema
# {
#       "htmlFileName": "",
#       "htmlContent": "",
#       "header": "",
#       "footer": "",
#       "customCss": "",
#       "s3Bucket": "",
# }
def html_to_pdf(request_json):
    file_name = request_json['htmlFileName']
    source_file = f'{DEFAULT_LOCATION}/{file_name}.html'
    with open(source_file, "w") as file:
        file.write(request_json['htmlContent'])

    pdf_file = f'{file_name}.pdf'
    pdf_file_location = f'{DEFAULT_LOCATION}/{pdf_file}'
    with sync_playwright() as p:
        browser = p.chromium.launch(headless=True)  # TODO: Consider adding args=["--disable-gpu", "--single-process"]
        page = browser.new_page()

        logging.info("Opening file - %s", source_file)
        subprocess.run(['ls', '-l', DEFAULT_LOCATION])
        page.goto(source_file)

        page.add_style_tag(content=request_json['customCss'])

        page.pdf(
            path=pdf_file_location,
            display_header_footer=True,
            header_template=request_json['header'],
            footer_template=request_json['footer'],
            format='A4'
        )

        browser.close()

    s3.upload_file(pdf_file_location, request_json['s3Bucket'], pdf_file)

    return {'status': 'SUCCESS'}

# api/app.py
from flask import Flask, request
from service.html_converter import html_to_pdf

# Creating the flask apps
app = Flask(__name__)

@app.route("/api/convert", methods=["POST"])
def convert_html_to_pdf():
    return html_to_pdf(request.json)

if __name__ == "__main__":
    app.run(host='0.0.0.0', port=8080)

Then our Dockerfile

FROM mcr.microsoft.com/playwright/python:v1.45.1-jammy

# Set the working directory
WORKDIR /app

# Copy the entire application into the container
COPY . /app

# Install requirements using pip (assuming 'requirements.1.0.1' is your requirements file)
RUN pip install -r requirements.txt

# Set the environment variable
ENV PYTHONPATH=/app \
    PWDEBUG=1

# Expose the port on which your application runs
EXPOSE 8080

# Specify the entry point command to start the application
ENTRYPOINT [ "python", "api/app.py" ]

Expected behavior

I expect the HTML to be converted to PDF

Actual behavior

Instead we encountered this error even though we already set headless=True

image

Additional context

Original reproduction

We originally implemented this in Java, where we encountered an earlier issue (see our original filed issue at playwright-java) which we were able to bypass it by following this custom Playwright Dockerfile for Alpine. We manually installed node and Chromium compatible with Alpine for Playwright to use.

However we arrived at the same "launched a headed browser" issue:

2024-07-29 18:56:45 ╔════════════════════════════════════════════════════════════════════════════════════════════════╗
2024-07-29 18:56:45 ║ Looks like you launched a headed browser without having a XServer running.                     ║
2024-07-29 18:56:45 ║ Set either 'headless: true' or use 'xvfb-run <your-playwright-app>' before running Playwright. ║
2024-07-29 18:56:45 ║                                                                                                ║
2024-07-29 18:56:45 ║ <3 Playwright Team                                                                             ║
2024-07-29 18:56:45 ╚════════════════════════════════════════════════════════════════════════════════════════════════╝
2024-07-29 18:56:45 Call log:
2024-07-29 18:56:45 <launching> /ms-playwright/chromium-1124/chrome-linux/chrome --disable-field-trial-config --disable-background-networking --enable-features=NetworkService,NetworkServiceInProcess --disable-background-timer-throttling --disable-backgrounding-occluded-windows --disable-back-forward-cache --disable-breakpad --disable-client-side-phishing-detection --disable-component-extensions-with-background-pages --disable-component-update --no-default-browser-check --disable-default-apps --disable-dev-shm-usage --disable-extensions --disable-features=ImprovedCookieControls,LazyFrameLoading,GlobalMediaControls,DestroyProfileOnBrowserClose,MediaRouter,DialMediaRouteProvider,AcceptCHFrame,AutoExpandDetailsElement,CertificateTransparencyComponentUpdater,AvoidUnnecessaryBeforeUnloadCheckSync,Translate,HttpsUpgrades,PaintHolding --allow-pre-commit-input --disable-hang-monitor --disable-ipc-flooding-protection --disable-popup-blocking --disable-prompt-on-repost --disable-renderer-backgrounding --force-color-profile=srgb --metrics-recording-only --no-first-run --enable-automation --password-store=basic --use-mock-keychain --no-service-autorun --export-tagged-pdf --disable-search-engine-choice-screen --unsafely-disable-devtools-self-xss-warnings --no-sandbox --disable-gpu --single-process --user-data-dir=/tmp/playwright_chromiumdev_profile-XXXXXXaocQe0 --remote-debugging-pipe --no-startup-window

Second reproduction

We then proceeded to use playwright-java's Dockerfile, meaning we fully switched to using Ubuntu from Alpine.

Still we arrived at the "launched a headed browser" issue.

Do note that in both cases, we ensured that the Chromium browser in the Java code had .setHeadless(true) already.

Environment

- Operating System: [Ubuntu 22.04 (Docker)]
- Browser: [Chromium]
- Python Version: [3.10.12]
- Other info: Docker base image used is https://hub.docker.com/r/microsoft/playwright-python

anobilisgorse avatar Jul 29 '24 13:07 anobilisgorse

Instead we encountered this error even though we already set headless=True

Do you mind providing us the full screenshot? Its cut off on the right side. I'd like to see if --headless is passed or not. If you don't specify headless it should be True by default.

We originally implemented this in Java, where we encountered an earlier issue https://github.com/microsoft/playwright-java/issues/1630 which we were able to bypass it by following this custom Playwright Dockerfile for Alpine. We manually installed node and Chromium compatible with Alpine for Playwright to use.

While Alpine is not officially supported, with a custom Node.js + Alpine Chromium it should work (except video recording - since it relies on a custom ffmpeg).


Since this seems to not work with official images, it might be related to the host machine of where your Docker is running. Does it work on your local machine / a different machine?

mxschmitt avatar Jul 29 '24 14:07 mxschmitt

Do you mind providing us the full screenshot? Its cut off on the right side. I'd like to see if --headless is passed or not. If you don't specify headless it should be True by default.

This is the full log already image

While Alpine is not officially supported, with a custom Node.js + Alpine Chromium it should work (except video recording - since it relies on a custom ffmpeg).

We already tried and somehow it did not work.

Since this seems to not work with official images, it might be related to the host machine of where your Docker is running. Does it work on your local machine / a different machine?

Yes, our original implementation is in Java - Spring Boot, and it runs perfectly in local run (Windows). When we deployed this to our DEV environment (Alpine Linux) that is where we encountered the error. We tried to replicate it in Docker and saw those logs.

We then switched to an Ubuntu image and used the official Playwright Docker image for Java, but still the same.

Then we did a POC in Python and used the official Playwright Docker image for Python, and once again we encountered the same error.

anobilisgorse avatar Jul 30 '24 10:07 anobilisgorse

Thank you for the full logs! So there is no --headless argument listed in the list, this means that you either in your code pass headless: false or have environment variables configured which launch Playwright as headed. I'm thinking about PWDEBUG. I think we don't have other env vars which influence this decision. Could you make sure this one is not set?

mxschmitt avatar Jul 30 '24 10:07 mxschmitt

this means that you either in your code pass headless: false

Please see the code above in Steps to reproduce, I already have it set. It's on the line with a #TODO comment.

I'm thinking about PWDEBUG. I think we don't have other env vars which influence this decision. Could you make sure this one is not set?

Got it let me try removing and let you know if it affects it in anyway.

anobilisgorse avatar Jul 30 '24 10:07 anobilisgorse

I'll close it for now, since you set the PWDEBUG env var, which starts the browser in headed, as per here. This env var is only useful for local scenarios, where you want to debug a specific Playwright script.

mxschmitt avatar Jul 31 '24 11:07 mxschmitt

sorry for reopening this issue. my os is Ubuntu Desktop on Google Cloud. When i run script with playwright , the same error occurred. How to resolve it in my situation. Thanks.

zqxyus avatar Aug 02 '24 10:08 zqxyus

sorry for reopening this issue. my os is Ubuntu Desktop on Google Cloud. When i run script with playwright , the same error occurred. How to resolve it in my situation. Thanks.

Please file a separate issue, since your issue looks different. Thanks.

mxschmitt avatar Aug 02 '24 10:08 mxschmitt