Python Selenium scraper
A Chrome browser scraper that renders JavaScript before extracting data. Good for social feeds, dashboards, or single-page apps.
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/python7"""8
9from __future__ import annotations10
11import asyncio12from urllib.parse import urljoin13
14from apify import Actor, Request15from selenium import webdriver16from selenium.webdriver.chrome.options import Options as ChromeOptions17from selenium.webdriver.common.by import By18
19# To run this Actor locally, you need to have the Selenium Chromedriver installed.20# Follow the installation guide at:21# https://www.selenium.dev/documentation/webdriver/getting_started/install_drivers/22# When running on the Apify platform, the Chromedriver is already included23# in the Actor's Docker image.24
25# Limit the crawl to max requests. Increase it to crawl more links.26MAX_REQUESTS_PER_CRAWL = 1027
28# Matches Playwright's default navigation timeout, which the sibling templates rely on.29PAGE_LOAD_TIMEOUT_SECS = 3030
31
32async def main() -> None:33 """Define a main entry point for the Apify Actor.34
35 This coroutine is executed using `asyncio.run()`, so it must remain an asynchronous function for proper execution.36 Asynchronous execution is required for communication with Apify platform, and it also enhances performance in37 the field of web scraping significantly.38 """39 # Enter the context of the Actor.40 async with Actor:41 # Retrieve the Actor input, and use default values if not provided.42 actor_input = await Actor.get_input() or {}43 start_urls = actor_input.get('start_urls', [{'url': 'https://apify.com'}])44 max_depth = actor_input.get('max_depth', 1)45
46 # Exit if no start URLs are provided.47 if not start_urls:48 Actor.log.info('No start URLs specified in Actor input, exiting...')49 await Actor.exit()50
51 # Open the default request queue for handling URLs to be processed.52 request_queue = await Actor.open_request_queue()53
54 # Enqueue the start URLs with an initial crawl depth of 0.55 for start_url in start_urls:56 url = start_url.get('url')57 Actor.log.info(f'Enqueuing {url} ...')58 new_request = Request.from_url(url, user_data={'depth': 0})59 await request_queue.add_request(new_request)60
61 # Launch a new Selenium Chrome WebDriver and configure it.62 Actor.log.info('Launching Chrome WebDriver...')63 chrome_options = ChromeOptions()64
65 if Actor.configuration.headless:66 chrome_options.add_argument('--headless')67
68 chrome_options.add_argument('--no-sandbox')69 chrome_options.add_argument('--disable-dev-shm-usage')70 driver = webdriver.Chrome(options=chrome_options)71
72 # Without this a page that never finishes loading blocks for 120s, the client timeout.73 driver.set_page_load_timeout(PAGE_LOAD_TIMEOUT_SECS)74
75 # Test WebDriver setup by navigating to an example page.76 driver.get('http://www.example.com')77 if driver.title != 'Example Domain':78 raise ValueError('Failed to open example page.')79
80 handled_requests = 081
82 # Process the URLs from the request queue.83 while handled_requests < MAX_REQUESTS_PER_CRAWL and (request := await request_queue.fetch_next_request()):84 url = request.url85
86 if not isinstance(request.user_data['depth'], (str, int)):87 raise TypeError('Request.depth is an enexpected type.')88
89 depth = int(request.user_data['depth'])90 Actor.log.info(f'Scraping {url} (depth={depth}) ...')91
92 try:93 # Navigate to the URL using Selenium WebDriver. Use asyncio.to_thread94 # for non-blocking execution.95 await asyncio.to_thread(driver.get, url)96
97 # If the current depth is less than max_depth, find nested links98 # and enqueue them.99 if depth < max_depth:100 for link in driver.find_elements(By.TAG_NAME, 'a'):101 link_href = link.get_attribute('href')102 link_url = urljoin(url, link_href)103
104 if link_url.startswith(('http://', 'https://')):105 Actor.log.info(f'Enqueuing {link_url} ...')106 new_request = Request.from_url(107 link_url,108 user_data={'depth': depth + 1},109 )110 await request_queue.add_request(new_request)111
112 # Extract the desired data.113 data = {114 'url': url,115 'title': driver.title,116 }117
118 # Store the extracted data to the default dataset.119 await Actor.push_data(data)120
121 except Exception:122 Actor.log.exception(f'Cannot extract data from {url}.')123
124 finally:125 # Mark the request as handled to ensure it is not processed again.126 await request_queue.mark_request_as_handled(request)127 handled_requests += 1128
129 driver.quit()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.
- 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
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_urlskey with a list of URLs to scrape and amax_depthkey 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_datamethod 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.exceptionmethod.
- Selenium controlled Chrome example
- Selenium Grid: what it is and how to set it up
- Web scraping with Selenium and Python
- Cypress vs. Selenium for web testing
- Python tutorials in Academy
- Video guide on getting scraped data using Apify API
- A short guide on how to build web scrapers using code templates:
BeautifulSoup crawler
Get data from every page on a site. Good for simple sites like blogs, news, or product listings, but it can't run client-side JavaScript. Uses BeautifulSoup, Python's most popular HTML parser.
Empty Python Actor
An Actor with the Apify SDK set up, so you can build any tool you need.
Python one-page scraper
Get data from one web page with BeautifulSoup. The simplest way to start scraping.
Python project managed by uv
A general-purpose Python Actor with its project and dependencies managed by the uv package manager. A minimal starting point for any use case.
Python multi-page scraper
Get data from multiple web pages with BeautifulSoup. Fast and light for simple sites.
Python Playwright scraper
A real-browser scraper that gets data HTTP scrapers miss. Good for social feeds, dashboards, or single-page apps.