BeautifulSoup + Requests
Example of a web scraper that uses Python Requests to scrape HTML from URLs provided on input, parses it using BeautifulSoup and saves results to storage.
from urllib.parse import urljoin
import requests
from apify import Actor
from bs4 import BeautifulSoup
async def main():
async with Actor:
# Read the Actor input
actor_input = await Actor.get_input() or {}
start_urls = actor_input.get('start_urls', [{ 'url': 'https://apify.com' }])
max_depth = actor_input.get('max_depth', 1)
if not start_urls:
Actor.log.info('No start URLs specified in actor input, exiting...')
await Actor.exit()
# Enqueue the starting URLs in the default request queue
default_queue = await Actor.open_request_queue()
for start_url in start_urls:
url = start_url.get('url')
Actor.log.info(f'Enqueuing {url} ...')
await default_queue.add_request({ 'url': url, 'userData': { 'depth': 0 }})
# Process the requests in the queue one by one
while request := await default_queue.fetch_next_request():
url = request['url']
depth = request['userData']['depth']
Actor.log.info(f'Scraping {url} ...')
try:
# Fetch the URL using `requests` and parse it using `BeautifulSoup`
response = requests.get(url)
soup = BeautifulSoup(response.content, 'html.parser')
# If we haven't reached the max depth,
# look for nested links and enqueue their targets
if depth < max_depth:
for link in soup.find_all('a'):
link_href = link.get('href')
link_url = urljoin(url, link_href)
if link_url.startswith(('http://', 'https://')):
Actor.log.info(f'Enqueuing {link_url} ...')
await default_queue.add_request({
'url': link_url,
'userData': {'depth': depth + 1 },
})
# Push the title of the page into the default dataset
title = soup.title.string if soup.title else None
await Actor.push_data({ 'url': url, 'title': title })
except:
Actor.log.exception(f'Cannot extract data from {url}.')
finally:
# Mark the request as handled so it's not processed again
await default_queue.mark_request_as_handled(request)
BeautifulSoup and Requests template
A template for web scraping data from websites enqueued from starting URL using Python. The URL of the web page is passed in via input, which is defined by the input schema. The template uses the Requests to get the HTML of the page and the Beautiful Soup to parse the data from it. Enqueued URLs are available in request queue. The data are then stored in a dataset where you can easily access them.
Included features
- Apify SDK for Python - a toolkit for building 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
- Requests - an elegant and simple HTTP library for Python
- Beautiful Soup - a Python library for pulling data out of HTML and XML files
How it works
This code is a Python script that uses Requests and Beautiful Soup 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 amax_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 0.
- The script processes the requests in the queue one by one, fetching the URL using Requests and parsing it using BeautifulSoup.
- 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, all the links) and pushes it to the default dataset using the
push_data
method of the Actor instance. - The script catches any exceptions that occur during the scraping process and logs an error message using the
Actor.log.exception
method. - This code demonstrates how to use Python and the Apify SDK to scrape web pages and extract specific data from them.
Resources
- BeautifulSoup Scraper
- Beautifulsoup Scraper tutorial
- Python tutorials in Academy
- Web scraping with Beautiful Soup and Requests
- Beautiful Soup vs. Scrapy for web scraping
- Integration with Zapier, Make, Google Drive, and others
- Video guide on getting scraped data using Apify API
- Video introduction to Python SDK
A short guide on how to build web scrapers using code templates: web scraper template
Scrape single page with provided URL with Requests and extract data from page's HTML with Beautiful Soup.
Crawler example that uses headless Chrome driven by Playwright to scrape a website. Headless browsers render JavaScript and can help when getting blocked.
Scraper example built with Selenium and headless Chrome browser to scrape a website and save the results to storage. A popular alternative to Playwright.
This example Scrapy spider scrapes page titles from URLs defined in input parameter. It shows how to use Apify SDK for Python and Scrapy pipelines to save results.
Empty template with basic structure for the Actor with Apify SDK that allows you to easily add your own functionality.