VOOZH about

URL: https://apify.com/templates/python-beautifulsoup

⇱ BeautifulSoup Β· Template Β· Apify


Back to template gallery

Language

πŸ‘ Image
python

Tools

πŸ‘ Image
beautifulsoup

Use cases

Web scraping

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/python
7"""
8
9from __future__ import annotations
10
11from urllib.parse import urljoin
12
13from apify import Actor, Request
14from bs4 import BeautifulSoup
15from httpx import AsyncClient
16
17
18asyncdefmain()->None:
19"""Define a main entry point for the Apify Actor.
20
21 This coroutine is executed using `asyncio.run()`, so it must remain an asynchronous function for proper execution.
22 Asynchronous execution is required for communication with Apify platform, and it also enhances performance in
23 the field of web scraping significantly.
24 """
25# Enter the context of the Actor.
26asyncwith Actor:
27# Retrieve the Actor input, and use default values if not provided.
28 actor_input =await Actor.get_input()or{}
29 start_urls = actor_input.get('start_urls',[{'url':'https://apify.com'}])
30 max_depth = actor_input.get('max_depth',1)
31
32# Exit if no start URLs are provided.
33ifnot start_urls:
34 Actor.log.info('No start URLs specified in Actor input, exiting...')
35await Actor.exit()
36
37# Open the default request queue for handling URLs to be processed.
38 request_queue =await Actor.open_request_queue()
39
40# Enqueue the start URLs with an initial crawl depth of 0.
41for start_url in start_urls:
42 url = start_url.get('url')
43 Actor.log.info(f'Enqueuing {url} ...')
44 new_request = Request.from_url(url, user_data={'depth':0})
45await request_queue.add_request(new_request)
46
47# Create an HTTPX client to fetch the HTML content of the URLs.
48asyncwith AsyncClient()as client:
49# Process the URLs from the request queue.
50while request :=await request_queue.fetch_next_request():
51 url = request.url
52
53ifnotisinstance(request.user_data['depth'],(str,int)):
54raise TypeError('Request.depth is an enexpected type.')
55
56 depth =int(request.user_data['depth'])
57 Actor.log.info(f'Scraping {url} (depth={depth}) ...')
58
59try:
60# Fetch the HTTP response from the specified URL using HTTPX.
61 response =await client.get(url, follow_redirects=True)
62
63# Parse the HTML content using Beautiful Soup.
64 soup = BeautifulSoup(response.content,'html.parser')
65
66# If the current depth is less than max_depth, find nested links
67# and enqueue them.
68if depth < max_depth:
69for link in soup.find_all('a'):
70 link_href = link.get('href')
71ifnotisinstance(link_href,str):
72continue
73 link_url = urljoin(url, link_href)
74
75if link_url.startswith(('http://','https://')):
76 Actor.log.info(f'Enqueuing {link_url} ...')
77 new_request = Request.from_url(
78 link_url,
79 user_data={'depth': depth +1},
80)
81await request_queue.add_request(new_request)
82
83# Extract the desired data.
84 data ={
85'url': url,
86'title': soup.title.string if soup.title elseNone,
87'h1s':[h1.text for h1 in soup.find_all('h1')],
88'h2s':[h2.text for h2 in soup.find_all('h2')],
89'h3s':[h3.text for h3 in soup.find_all('h3')],
90}
91
92# Store the extracted data to the default dataset.
93await Actor.push_data(data)
94
95except Exception:
96 Actor.log.exception(f'Cannot extract data from {url}.')
97
98finally:
99# Mark the request as handled to ensure it is not processed again.
100await request_queue.mark_request_as_handled(new_request)

Python BeautifulSoup 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 HTTPX  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 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
  • HTTPX  - library for making asynchronous HTTP requests in 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 HTTPX 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 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 0.
  • The script processes the requests in the queue one by one, fetching the URL using HTTPX 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

Crawlee + BeautifulSoup

Crawl and scrape websites using Crawlee and BeautifulSoup. Start from a URL and store results to your Apify dataset.

Starter

Empty Python project

Start with Apify SDK already set up, then build any features you need.

Starter

One‑Page HTML Scraper with BeautifulSoup

Scrape single page with provided URL with HTTPX and extract data from page's HTML with Beautiful Soup.

Starter

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.

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.

Standby Python project

Start with a working Actor in Standby mode that stays ready in the background, then build any features you need.

Starter

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.