Running Playwright Tests in Python with Flask on Cloud Run

Automating browser tasks is a breeze with Playwright, and integrating it into a cloud-based service can take your automation capabilities to the next level. In this blog post, we’ll walk you through setting up a Python-based application that uses Flask and Playwright, deploy it to Google Cloud Run, and enable running browser tests through a simple API.


Step 1: Setting Up the Application

We’ll build a Flask app that exposes a POST API to accept a test URL and execute a Playwright test on that URL. To simplify the setup, we’ll keep everything in a single file:

Flask App with Playwright Integration

from flask import Flask, request, jsonify

from playwright.sync_api import sync_playwright

app = Flask(__name__)

# Playwright Test Function

def run_test(test_url):

with sync_playwright() as p:

browser = p.chromium.launch()

page = browser.new_page()

page.goto(test_url)

title = page.title()

browser.close()

return f"Test completed for {test_url}: {title}"

# Flask Route

@app.route("/", methods=["POST"])

def execute_test():

# Get JSON payload

data = request.json

if not data or "test_url" not in data:

return jsonify({"error": "Missing 'test_url' in request body"}), 400

test_url = data["test_url"]

try:

result = run_test(test_url)

return jsonify({"message": result}), 200

except Exception as e:

return jsonify({"error": str(e)}), 500

if name == "__main__":

app.run(host="0.0.0.0", port=8080)

Key Features

  1. Route Definition: The / route listens for POST requests and expects a JSON payload containing test_url.

  2. Error Handling: Proper validation ensures meaningful error messages for missing or invalid input.

  3. Playwright Test: The run_test function launches a browser, navigates to the provided URL, fetches the page title, and returns the result.


Step 2: Dockerizing the Application

To deploy the application on Cloud Run, we’ll containerize it using Docker. Create a Dockerfile in the same directory as the app.py file.

Dockerfile

FROM python:3.10-slim

# Install Playwright and Flask

RUN apt-get update && apt-get install -y wget curl gnupg libatk-bridge2.0-0 libnss3 libnspr4 && rm -rf /var/lib/apt/lists/*

RUN pip install flask playwright

# Install browser binaries for Playwright

RUN python -m playwright install

# Copy application code

WORKDIR /app

COPY app.py .

# Expose port 8080

EXPOSE 8080

# Run the application

CMD ["python", "app.py"]


Step 3: Deploying to Google Cloud Run

Once your application is containerized, you can deploy it to Google Cloud Run. Follow these steps:

Step 3.1: Build and Push Docker Image

  1. Build the Docker image: docker build -t gcr.io/<YOUR_PROJECT_ID>/playwright-app .

  2. Push the image to Google Container Registry (GCR): docker push gcr.io/<YOUR_PROJECT_ID>/playwright-app

Step 3.2: Deploy to Cloud Run

Deploy the service to Cloud Run:
gcloud run deploy playwright-app \ --image=gcr.io/<YOUR_PROJECT_ID>/playwright-app \ --platform managed \ --region <YOUR_REGION> \--allow-unauthenticated

  1. Note the URL provided by Cloud Run after successful deployment.

Step 4: Passing Parameters to the Cloud Run Service

To test specific scenarios, you can pass parameters to your Cloud Run service using a JSON payload. This can be done via tools like curl, Postman, or any HTTP client.

Example JSON Payload

{

"test_url": "https://example.com"

}

Example curl Command

curl -X POST https://<YOUR_CLOUD_RUN_URL> \

-H "Content-Type: application/json" \

-d '{"test_url": "https://example.com"}'

Expected Response

{

"message": "Test completed for https://example.com: Example Domain"

}


Step 5: Testing the Application

You can test your Cloud Run service using tools like curl or Postman, as shown above. Modify the test_url parameter in the payload to run tests on different URLs.


Troubleshooting

Common Issues

  1. Playwright Dependencies: Ensure all required dependencies are installed. The Dockerfile includes the necessary packages.

  2. Port Configuration: Cloud Run expects the application to listen on port 8080.

  3. Permission Errors: Ensure the Docker image is accessible by Cloud Run.

Debugging Logs

Use the following command to view Cloud Run logs:

gcloud run services logs read playwright-app --region <YOUR_REGION>


Conclusion

In this blog, we’ve shown how to build a Python-based API that leverages Playwright for browser automation, deploy it to Google Cloud Run, and pass parameters to execute specific tests. This setup is ideal for scenarios like website testing, data scraping, or automating repetitive browser tasks. With Cloud Run’s scalability, your service is ready to handle increased demand effortlessly.

Try it out and unlock the power of automated browser testing in the cloud!