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.

Language

python

Tools

selenium

Use cases

Web scraping

src/main.py

src/__main__.py

1"""
2This module defines the `main()` coroutine for the Apify Actor, executed from the `__main__.py` file.
3
4Feel free to modify this file to suit your specific needs.
5
6To build Apify Actors, utilize the Apify SDK toolkit, read more at the official documentation:
7https://docs.apify.com/sdk/python
8"""
9
10from urllib.parse import urljoin
11
12from selenium import webdriver
13from selenium.webdriver.chrome.options import Options as ChromeOptions
14from selenium.webdriver.common.by import By
15
16from apify import Actor
17
18# To run this Actor locally, you need to have the Selenium Chromedriver installed.
19# https://www.selenium.dev/documentation/webdriver/getting_started/install_drivers/
20# When running on the Apify platform, it is already included in the Actor's Docker image.
21
22
23async def main() -> None:
24    """
25    The main coroutine is being executed using `asyncio.run()`, 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': 'https://apify.com'}])
33        max_depth = actor_input.get('max_depth', 1)
34
35        if not start_urls:
36            Actor.log.info('No start URLs specified in actor input, exiting...')
37            await Actor.exit()
38
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            Actor.log.info(f'Enqueuing {url} ...')
44            await default_queue.add_request({'url': url, 'userData': {'depth': 0}})
45
46        # Launch a new Selenium Chrome WebDriver
47        Actor.log.info('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)
54
55        driver.get('http://www.example.com')
56        assert driver.title == 'Example Domain'
57
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            Actor.log.info(f'Scraping {url} ...')
63
64            try:
65                # Open the URL in the Selenium WebDriver
66                driver.get(url)
67
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                            Actor.log.info(f'Enqueuing {link_url} ...')
76                            await default_queue.add_request({
77                                'url': link_url,
78                                'userData': {'depth': depth + 1},
79                            })
80
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)
88
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.

Resources

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.