Scrapers¶
scrapers ¶
Assembly: Foo
Filename: scrapers.py
Author: Terry D. Eppler
Created: 05-31-2022
Last Modified By: Terry D. Eppler
Last Modified On: 05-01-2025
Foo is a python framework for web scraping information into ML pipelines.
Copyright © 2025 Terry Eppler
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
You can contact me at: terryeppler@gmail.com or eppler.terry@epa.gov
Classes¶
Extractor ¶
Provide shared state for HTML extraction workflows.
Purpose
Defines the raw-document, parsed-document, and extracted-text state used by concrete extractors. Subclasses populate these members while retrieving and transforming source content for display, indexing, or model-facing workflows.
Attributes:
| Name | Type | Description |
|---|---|---|
raw_html |
Optional[str]
|
Unmodified HTML retained before parsing or text conversion. |
extracted_text |
Optional[str]
|
Plain text produced from the current HTML document. |
soup |
Optional[BeautifulSoup]
|
Parsed document tree for the current HTML source. |
Purpose
Creates an empty extraction context that concrete subclasses can populate without performing network, parsing, or transformation work during construction.
Returns:
| Name | Type | Description |
|---|---|---|
None |
None
|
Initializes instance state without returning a value. |
Source code in scrapers.py
WebExtractor ¶
Bases: Extractor
Fetch and extract structured content from HTML pages.
Purpose
Wraps synchronous HTTP retrieval with reusable HTML parsing operations. The class stores
validated request arguments as instance state before invoking requests, then exposes
plain-text conversion, semantic element extraction, link and image discovery, and dynamic
tool-schema construction for downstream ML and model orchestration workflows.
Attributes:
| Name | Type | Description |
|---|---|---|
agents |
Optional[str]
|
User-agent value sent with HTTP requests. |
url |
Optional[str]
|
Normalized URL used by the current request. |
html |
Optional[str]
|
HTML currently being transformed or parsed. |
timeout |
Optional[int]
|
Maximum request duration in seconds. |
headers |
Optional[Dict[str, str]]
|
HTTP headers supplied to the wrapped requests client. |
response |
Optional[Response]
|
Most recent HTTP response returned by |
result |
Optional[Result]
|
Canonical Foo result created from the most recent response. |
re_tag |
Optional[Pattern]
|
Pattern used to remove remaining HTML tags. |
re_ws |
Optional[Pattern]
|
Pattern used to collapse repeated whitespace. |
function |
Optional[str]
|
Function name assigned to the current tool schema. |
tool |
Optional[str]
|
Service name assigned to the current tool schema. |
description |
Optional[str]
|
Human-readable behavior description for the current schema. |
parameters |
Optional[Dict[str, Any]]
|
JSON Schema property definitions for tool arguments. |
required |
Optional[List[str]]
|
Required argument names included in the current schema. |
Purpose
Prepares request headers, timeout defaults, regular-expression helpers, response state, and schema state used by subsequent retrieval and extraction operations. Construction does not perform network activity.
Returns:
| Name | Type | Description |
|---|---|---|
None |
None
|
Initializes instance state without returning a value. |
Source code in scrapers.py
Methods:¶
scrape ¶
Fetch an HTML resource and return its canonical result.
Purpose
Validates and stores the request URL and timeout before invoking requests.get. The
method retains the response, verifies its status, captures the response HTML, prepares a
BeautifulSoup document tree, and returns Foo's normalized Result representation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
url
|
str
|
Absolute HTTP or HTTPS URL of the resource to retrieve. |
required |
time
|
int
|
Maximum number of seconds permitted for the HTTP request. |
10
|
Returns:
| Type | Description |
|---|---|
Result | None
|
Result | None: Canonical Foo result containing the successful HTTP response. |
Raises:
| Type | Description |
|---|---|
Error
|
Re-raised after the source exception is wrapped with structured diagnostic metadata. |
Source code in scrapers.py
html_to_text ¶
Convert HTML markup into compact plain text.
Purpose
Stores the source document before removing script and style blocks, introducing readable boundaries around block elements, stripping residual tags, and collapsing repeated whitespace. The resulting text is suitable for indexing, display, or model input.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
html
|
str
|
Raw HTML document to transform. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
Normalized plain text extracted from the HTML document. |
Raises:
| Type | Description |
|---|---|
Error
|
Re-raised after the source exception is wrapped with structured diagnostic metadata. |
Source code in scrapers.py
scrape_paragraphs ¶
Extract paragraph text from an HTML page.
Purpose
Retrieves the supplied page through the configured request state and returns non-empty text from each paragraph element in document order.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
uri
|
str
|
Fully qualified URL of the HTML page to inspect. |
required |
Returns:
| Type | Description |
|---|---|
List[str] | None
|
List[str] | None: Non-empty paragraph strings in document order. |
Raises:
| Type | Description |
|---|---|
Error
|
Re-raised after the source exception is wrapped with structured diagnostic metadata. |
Source code in scrapers.py
scrape_lists ¶
Extract list-item text from an HTML page.
Purpose
Retrieves the supplied page and returns the readable content of non-empty li elements,
providing a simple sequence for indexing or downstream content analysis.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
uri
|
str
|
Fully qualified URL of the HTML page to inspect. |
required |
Returns:
| Type | Description |
|---|---|
List[str] | None
|
List[str] | None: Non-empty list-item strings in document order. |
Raises:
| Type | Description |
|---|---|
Error
|
Re-raised after the source exception is wrapped with structured diagnostic metadata. |
Source code in scrapers.py
scrape_tables ¶
Extract flattened table-cell text from an HTML page.
Purpose
Retrieves the target page and flattens non-empty header and data cells from every table into a document-order sequence suitable for quick inspection or text-based indexing.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
uri
|
str
|
Fully qualified URL of the HTML page to inspect. |
required |
Returns:
| Type | Description |
|---|---|
List[str] | None
|
List[str] | None: Non-empty |
Raises:
| Type | Description |
|---|---|
Error
|
Re-raised after the source exception is wrapped with structured diagnostic metadata. |
Source code in scrapers.py
scrape_articles ¶
Extract article-level text from an HTML page.
Purpose
Retrieves the target page and consolidates readable text from each semantic article
element so callers can treat article blocks as document-like units.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
uri
|
str
|
Fully qualified URL of the HTML page to inspect. |
required |
Returns:
| Type | Description |
|---|---|
List[str] | None
|
List[str] | None: Non-empty article text blocks in document order. |
Raises:
| Type | Description |
|---|---|
Error
|
Re-raised after the source exception is wrapped with structured diagnostic metadata. |
Source code in scrapers.py
scrape_headings ¶
Extract heading text from an HTML page.
Purpose
Retrieves the target page and returns visible text from h1 through h6 elements,
providing a structural outline for summarization, navigation, or content inspection.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
uri
|
str
|
Fully qualified URL of the HTML page to inspect. |
required |
Returns:
| Type | Description |
|---|---|
List[str] | None
|
List[str] | None: Non-empty heading strings in document order. |
Raises:
| Type | Description |
|---|---|
Error
|
Re-raised after the source exception is wrapped with structured diagnostic metadata. |
Source code in scrapers.py
scrape_divisions ¶
Extract division text from an HTML page.
Purpose
Retrieves the target page and returns cleaned text from generic div containers,
providing broad coverage for pages that do not use semantic content elements.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
uri
|
str
|
Fully qualified URL of the HTML page to inspect. |
required |
Returns:
| Type | Description |
|---|---|
List[str] | None
|
List[str] | None: Non-empty division text blocks in document order. |
Raises:
| Type | Description |
|---|---|
Error
|
Re-raised after the source exception is wrapped with structured diagnostic metadata. |
Source code in scrapers.py
scrape_sections ¶
Extract semantic section text from an HTML page.
Purpose
Retrieves the target page and returns readable content from semantic section elements,
preserving page-level content groupings for indexing or analysis.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
uri
|
str
|
Fully qualified URL of the HTML page to inspect. |
required |
Returns:
| Type | Description |
|---|---|
List[str] | None
|
List[str] | None: Non-empty section text blocks in document order. |
Raises:
| Type | Description |
|---|---|
Error
|
Re-raised after the source exception is wrapped with structured diagnostic metadata. |
Source code in scrapers.py
scrape_blockquotes ¶
Extract blockquote text from an HTML page.
Purpose
Retrieves the target page and returns readable text from semantic blockquote elements,
capturing quoted or cited material separately from surrounding prose.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
uri
|
str
|
Fully qualified URL of the HTML page to inspect. |
required |
Returns:
| Type | Description |
|---|---|
List[str] | None
|
List[str] | None: Non-empty blockquote strings in document order. |
Raises:
| Type | Description |
|---|---|
Error
|
Re-raised after the source exception is wrapped with structured diagnostic metadata. |
Source code in scrapers.py
scrape_hyperlinks ¶
Extract hyperlink references from an HTML page.
Purpose
Retrieves the target page and returns non-empty href values from anchor elements.
References remain in their source form so callers can decide whether and how to resolve
relative paths.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
uri
|
str
|
Fully qualified URL of the HTML page to inspect. |
required |
Returns:
| Type | Description |
|---|---|
List[str] | None
|
List[str] | None: Non-empty hyperlink references in document order. |
Raises:
| Type | Description |
|---|---|
Error
|
Re-raised after the source exception is wrapped with structured diagnostic metadata. |
Source code in scrapers.py
scrape_images ¶
Extract image references from an HTML page.
Purpose
Retrieves the target page and returns non-empty src values from image elements.
References remain in their source form so callers can resolve or filter them according to
the surrounding workflow.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
uri
|
str
|
Fully qualified URL of the HTML page to inspect. |
required |
Returns:
| Type | Description |
|---|---|
List[str] | None
|
List[str] | None: Non-empty image source references in document order. |
Raises:
| Type | Description |
|---|---|
Error
|
Re-raised after the source exception is wrapped with structured diagnostic metadata. |
Source code in scrapers.py
create_schema ¶
create_schema(
function: str,
tool: str,
description: str,
parameters: dict,
required: list[str],
) -> Dict[str, str] | None
Create a JSON-compatible tool schema.
Purpose
Validates and stores schema inputs before constructing a function definition that names the wrapped service, describes its behavior, and declares JSON Schema properties and required arguments for model tool-calling workflows.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
function
|
str
|
Function name exposed to the model or orchestration layer. |
required |
tool
|
str
|
Service or system used by the generated function. |
required |
description
|
str
|
Human-readable explanation of the function behavior. |
required |
parameters
|
dict
|
Mapping of parameter names to JSON Schema fragments. |
required |
required
|
list[str]
|
Required parameter names. When |
required |
Returns:
| Type | Description |
|---|---|
Dict[str, str] | None
|
Dict[str, str] | None: JSON-compatible function schema. |
Raises:
| Type | Description |
|---|---|
Error
|
Re-raised after the source exception is wrapped with structured diagnostic metadata. |
Source code in scrapers.py
Functions:¶
throw_if ¶
Throw if.
Purpose
Validates that a required argument contains a usable value so failures occur before provider, filesystem, or parsing work begins.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Argument name included in validation error messages. |
required |
value
|
object
|
Candidate value to validate or normalize. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
None |
None
|
This method updates instance state or validates input and does not return a value. |
Raises:
| Type | Description |
|---|---|
ValueError
|
Raised when the method cannot satisfy its documented value requirement. |