Language
π Image
python
Tools
π Image
selenium
π Image
chrome
Use cases
Web scraping
Automation
Features
my_actor/main.py
my_actor/__main__.py
1"""Module defines the main entry point for the Apify Actor.23Feel free to modify this file to suit your specific needs.45To build Apify Actors, utilize the Apify SDK toolkit, read more at the official documentation:6https://docs.apify.com/sdk/python7"""89from __future__ import annotations1011import asyncio12from urllib.parse import urljoin1314from apify import Actor, Request15from selenium import webdriver16from selenium.webdriver.chrome.options import Options as ChromeOptions17from selenium.webdriver.common.by import By1819# 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.242526asyncdefmain()->None:27"""Define a main entry point for the Apify Actor.2829 This coroutine is executed using `asyncio.run()`, so it must remain an asynchronous function for proper execution.30 Asynchronous execution is required for communication with Apify platform, and it also enhances performance in31 the field of web scraping significantly.32 """33# Enter the context of the Actor.34asyncwith Actor:35# Retrieve the Actor input, and use default values if not provided.36 actor_input =await Actor.get_input()or{}37 start_urls = actor_input.get('start_urls',[{'url':'https://apify.com'}])38 max_depth = actor_input.get('max_depth',1)3940# Exit if no start URLs are provided.41ifnot start_urls:42 Actor.log.info('No start URLs specified in Actor input, exiting...')43await Actor.exit()4445# Open the default request queue for handling URLs to be processed.46 request_queue =await Actor.open_request_queue()4748# Enqueue the start URLs with an initial crawl depth of 0.49for start_url in start_urls:50 url = start_url.get('url')51 Actor.log.info(f'Enqueuing {url} ...')52 new_request = Request.from_url(url, user_data={'depth':0})53await request_queue.add_request(new_request)5455# Launch a new Selenium Chrome WebDriver and configure it.56 Actor.log.info('Launching Chrome WebDriver...')57 chrome_options = ChromeOptions()5859if Actor.configuration.headless:60 chrome_options.add_argument('--headless')6162 chrome_options.add_argument('--no-sandbox')63 chrome_options.add_argument('--disable-dev-shm-usage')64 driver = webdriver.Chrome(options=chrome_options)6566# Test WebDriver setup by navigating to an example page.67 driver.get('http://www.example.com')68if driver.title !='Example Domain':69raise ValueError('Failed to open example page.')7071# Process the URLs from the request queue.72while request :=await request_queue.fetch_next_request():73 url = request.url7475ifnotisinstance(request.user_data['depth'],(str,int)):76raise TypeError('Request.depth is an enexpected type.')7778 depth =int(request.user_data['depth'])79 Actor.log.info(f'Scraping {url} (depth={depth}) ...')8081try:82# Navigate to the URL using Selenium WebDriver. Use asyncio.to_thread83# for non-blocking execution.84await asyncio.to_thread(driver.get, url)8586# If the current depth is less than max_depth, find nested links87# and enqueue them.88if depth < max_depth:89for link in driver.find_elements(By.TAG_NAME,'a'):90 link_href = link.get_attribute('href')91 link_url = urljoin(url, link_href)9293if link_url.startswith(('http://','https://')):94 Actor.log.info(f'Enqueuing {link_url} ...')95 new_request = Request.from_url(96 link_url,97 user_data={'depth': depth +1},98)99await request_queue.add_request(new_request)100101# Extract the desired data.102 data ={103'url': url,104'title': driver.title,105}106107# Store the extracted data to the default dataset.108await Actor.push_data(data)109110except Exception:111 Actor.log.exception(f'Cannot extract data from {url}.')112113finally:114# Mark the request as handled to ensure it is not processed again.115await request_queue.mark_request_as_handled(request)116117 driver.quit()Python 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_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.
Resources
- 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:
Related templates
Crawlee + BeautifulSoup
Crawl and scrape websites using Crawlee and BeautifulSoup. Start from a URL and store results to your Apify dataset.
Empty Python project
Start with Apify SDK already set up, then build any features you need.
OneβPage HTML Scraper with BeautifulSoup
Scrape single page with provided URL with HTTPX and extract data from page's HTML with Beautiful Soup.
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.
Playwright + Chrome
Crawler example that uses headless Chrome driven by Playwright to scrape a website. Headless browsers render JavaScript and can help when getting blocked.
Standby Python project
Start with a working Actor in Standby mode that stays ready in the background, then build any features you need.
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.
