VOOZH about

URL: https://apify.com/templates/python-playwright

⇱ Playwright + Chrome Β· Template Β· Apify


Back to template gallery

Language

πŸ‘ Image
python

Tools

Use cases

Web scraping

Automation

my_actor/main.py

my_actor/__main__.py

1"""Module defines the main entry point for the Apify Actor.
2
3Feel free to modify this file to suit your specific needs.
4
5To build Apify Actors, utilize the Apify SDK toolkit, read more at the official documentation:
6https://docs.apify.com/sdk/python
7"""
8
9from __future__ import annotations
10
11from urllib.parse import urljoin
12
13from apify import Actor, Request
14from playwright.async_api import async_playwright
15
16# Note: To run this Actor locally, ensure that Playwright browsers are installed.
17# Run `playwright install --with-deps` in the Actor's virtual environment to install them.
18# When running on the Apify platform, these dependencies are already included
19# in the Actor's Docker image.
20
21
22asyncdefmain()->None:
23"""Define a main entry point for the Apify Actor.
24
25 This coroutine is executed using `asyncio.run()`, so it must remain an asynchronous function for proper execution.
26 Asynchronous execution is required for communication with Apify platform, and it also enhances performance in
27 the field of web scraping significantly.
28 """
29# Enter the context of the Actor.
30asyncwith Actor:
31# Retrieve the Actor input, and use default values if not provided.
32 actor_input =await Actor.get_input()or{}
33 start_urls = actor_input.get('start_urls',[{'url':'https://apify.com'}])
34 max_depth = actor_input.get('max_depth',1)
35
36# Exit if no start URLs are provided.
37ifnot start_urls:
38 Actor.log.info('No start URLs specified in Actor input, exiting...')
39await Actor.exit()
40
41# Open the default request queue for handling URLs to be processed.
42 request_queue =await Actor.open_request_queue()
43
44# Enqueue the start URLs with an initial crawl depth of 0.
45for start_url in start_urls:
46 url = start_url.get('url')
47 Actor.log.info(f'Enqueuing {url} ...')
48 new_request = Request.from_url(url, user_data={'depth':0})
49await request_queue.add_request(new_request)
50
51 Actor.log.info('Launching Playwright...')
52
53# Launch Playwright and open a new browser context.
54asyncwith async_playwright()as playwright:
55# Configure the browser to launch in headless mode as per Actor configuration.
56 browser =await playwright.chromium.launch(
57 headless=Actor.configuration.headless,
58 args=['--disable-gpu'],
59)
60 context =await browser.new_context()
61
62# Process the URLs from the request queue.
63while request :=await request_queue.fetch_next_request():
64 url = request.url
65
66ifnotisinstance(request.user_data['depth'],(str,int)):
67raise TypeError('Request.depth is an unexpected type.')
68
69 depth =int(request.user_data['depth'])
70 Actor.log.info(f'Scraping {url} (depth={depth}) ...')
71
72try:
73# Open a new page in the browser context and navigate to the URL.
74 page =await context.new_page()
75await page.goto(url)
76
77# If the current depth is less than max_depth, find nested links
78# and enqueue them.
79if depth < max_depth:
80for link inawait page.locator('a').all():
81 link_href =await link.get_attribute('href')
82 link_url = urljoin(url, link_href)
83
84if link_url.startswith(('http://','https://')):
85 Actor.log.info(f'Enqueuing {link_url} ...')
86 new_request = Request.from_url(
87 link_url,
88 user_data={'depth': depth +1},
89)
90await request_queue.add_request(new_request)
91
92# Extract the desired data.
93 data ={
94'url': url,
95'title':await page.title(),
96}
97
98# Store the extracted data to the default dataset.
99await Actor.push_data(data)
100
101except Exception:
102 Actor.log.exception(f'Cannot extract data from {url}.')
103
104finally:
105await page.close()
106# Mark the request as handled to ensure it is not processed again.
107await request_queue.mark_request_as_handled(request)

Python Playwright template

Included features

  • Apify SDK  for Python - a toolkit for building Apify Actors  and scrapers in Python
  • Input schema  - define and easily validate a schema for your Actor's input
  • Request queue  - queues into which you can put the URLs you want to scrape
  • Dataset  - store structured data where each object stored has the same attributes
  • Playwright  - a browser automation library

Resources

Crawlee + BeautifulSoup

Crawl and scrape websites using Crawlee and BeautifulSoup. Start from a URL and store results to your Apify dataset.

Starter

Empty Python project

Start with Apify SDK already set up, then build any features you need.

Starter

One‑Page HTML Scraper with BeautifulSoup

Scrape single page with provided URL with HTTPX and extract data from page's HTML with Beautiful Soup.

Starter

BeautifulSoup

Example of a web scraper that uses Python HTTPX to scrape HTML from URLs provided on input, parses it using BeautifulSoup and saves results to storage.

Selenium + Chrome

Scraper example built with Selenium and headless Chrome browser to scrape a website and save the results to storage. A popular alternative to Playwright.

Standby Python project

Start with a working Actor in Standby mode that stays ready in the background, then build any features you need.

Starter

Already have a solution in mind?

Sign up for a free Apify account and deploy your code to the platform in just a few minutes! If you want a head start without coding it yourself, browse our Store of existing solutions.