Back to template gallery

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.





Use cases

Web scraping



2This module defines the `main()` coroutine for the Apify Actor, executed from the `` file.
4Feel free to modify this file to suit your specific needs.
6To build Apify Actors, utilize the Apify SDK toolkit, read more at the official documentation:
10from urllib.parse import urljoin
12from selenium import webdriver
13from import Options as ChromeOptions
14from import By
16from apify import Actor
18# To run this Actor locally, you need to have the Selenium Chromedriver installed.
20# When running on the Apify platform, it is already included in the Actor's Docker image.
23async def main() -> None:
24    """
25    The main coroutine is being executed using ``, so do not attempt to make a normal function
26    out of it, it will not work. Asynchronous execution is required for communication with Apify platform,
27    and it also enhances performance in the field of web scraping significantly.
28    """
29    async with Actor:
30        # Read the Actor input
31        actor_input = await Actor.get_input() or {}
32        start_urls = actor_input.get('start_urls', [{'url': ''}])
33        max_depth = actor_input.get('max_depth', 1)
35        if not start_urls:
36  'No start URLs specified in actor input, exiting...')
37            await Actor.exit()
39        # Enqueue the starting URLs in the default request queue
40        default_queue = await Actor.open_request_queue()
41        for start_url in start_urls:
42            url = start_url.get('url')
43  'Enqueuing {url} ...')
44            await default_queue.add_request({'url': url, 'userData': {'depth': 0}})
46        # Launch a new Selenium Chrome WebDriver
47'Launching Chrome WebDriver...')
48        chrome_options = ChromeOptions()
49        if Actor.config.headless:
50            chrome_options.add_argument('--headless')
51        chrome_options.add_argument('--no-sandbox')
52        chrome_options.add_argument('--disable-dev-shm-usage')
53        driver = webdriver.Chrome(options=chrome_options)
55        driver.get('')
56        assert driver.title == 'Example Domain'
58        # Process the requests in the queue one by one
59        while request := await default_queue.fetch_next_request():
60            url = request['url']
61            depth = request['userData']['depth']
62  'Scraping {url} ...')
64            try:
65                # Open the URL in the Selenium WebDriver
66                driver.get(url)
68                # If we haven't reached the max depth,
69                # look for nested links and enqueue their targets
70                if depth < max_depth:
71                    for link in driver.find_elements(By.TAG_NAME, 'a'):
72                        link_href = link.get_attribute('href')
73                        link_url = urljoin(url, link_href)
74                        if link_url.startswith(('http://', 'https://')):
75                  'Enqueuing {link_url} ...')
76                            await default_queue.add_request({
77                                'url': link_url,
78                                'userData': {'depth': depth + 1},
79                            })
81                # Push the title of the page into the default dataset
82                title = driver.title
83                await Actor.push_data({'url': url, 'title': title})
84            except Exception:
85                Actor.log.exception(f'Cannot extract data from {url}.')
86            finally:
87                await default_queue.mark_request_as_handled(request)
89        driver.quit()

Selenium & Chrome template

A template example built with Selenium and a headless Chrome browser to scrape a website and save the results to storage. The URL of the web page is passed in via input, which is defined by the input schema. The template uses the Selenium WebDriver to load and process the page. Enqueued URLs are stored in the default request queue. The data are then stored in the default dataset where you can easily access them.

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
  • Selenium - a browser automation library

How it works

This code is a Python script that uses Selenium to scrape web pages and extract data from them. Here's a brief overview of how it works:

  • The script reads the input data from the Actor instance, which is expected to contain a start_urls key with a list of URLs to scrape and a max_depth key with the maximum depth of nested links to follow.
  • The script enqueues the starting URLs in the default request queue and sets their depth to 1.
  • The script processes the requests in the queue one by one, fetching the URL using requests and parsing it using Selenium.
  • If the depth of the current request is less than the maximum depth, the script looks for nested links in the page and enqueues their targets in the request queue with an incremented depth.
  • The script extracts the desired data from the page (in this case, titles of each page) and pushes them to the default dataset using the push_data method of the Actor instance.
  • The script catches any exceptions that occur during the web scraping process and logs an error message using the Actor.log.exception method.


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.