API Documentation

This part of the documentation covers the interfaces used to develop with amazon-orders.

Main Interface

class amazonorders.orders.AmazonOrders(amazon_session, debug=None, config=None)[source]

Bases: object

Using an authenticated AmazonSession, can be used to query Amazon for Order details and history.

amazon_session: AmazonSession

The session to use for requests.

config: AmazonOrdersConfig

The config to use.

debug: bool

Setting logger to DEBUG will send output to stderr.

get_order(order_id, clone=None)[source]

Get the full details for a given Amazon Order ID.

Parameters:
  • order_id (str) – The Amazon Order ID to lookup.

  • clone (Optional[Order]) – If a partially populated version of the Order has already been fetched from history.

Return type:

Order

Returns:

The requested Order.

get_invoice(order_id)[source]

Get the print-friendly invoice page for a given Amazon Order ID, returning the response (including its parsed HTML) so callers can render or print the page.

Parameters:

order_id (str) – The Amazon Order ID to lookup.

Return type:

AmazonSessionResponse

Returns:

The invoice page response.

get_order_history(year=None, start_index=None, full_details=False, keep_paging=True, time_filter=None)[source]

Get the Amazon Order history for a given time period.

Parameters:
  • year (Optional[int]) – The year for which to get history. Ignored if time_filter is provided. Defaults to the current year if neither year nor time_filter is specified.

  • start_index (Optional[int]) – The index of the Order from which to start fetching in the history. See index to correlate, or if a call to this method previously errored out, see index in the exception’s meta to continue paging where it left off.

  • full_details (bool) – Get the full details for each Order in the history. This will execute an additional request per Order.

  • keep_paging (bool) – False if only one page should be fetched.

  • time_filter (Optional[str]) – The time filter to use. Supported values are "last30" (last 30 days), "months-3" (past 3 months), or "year-YYYY" (specific year). If provided, this takes precedence over the year parameter.

Return type:

List[Order]

Returns:

A list of the requested Orders.

class amazonorders.transactions.AmazonTransactions(amazon_session, debug=None, config=None)[source]

Bases: object

Using an authenticated AmazonSession, can be used to query Amazon for Transaction details and history.

amazon_session: AmazonSession

The session to use for requests.

config: AmazonOrdersConfig

The config to use.

debug: bool

Setting logger to DEBUG will send output to stderr.

get_transactions(days=365, next_page_data=None, keep_paging=True, order_id=None)[source]

Get Amazon Transaction history for a given number of days, or for a single Order.

Parameters:
  • days (int) – The number of days worth of Transactions to get. Ignored when order_id is given.

  • next_page_data (Optional[Dict[str, Any]]) – If a call to this method previously errored out, passing the exception’s meta will continue paging where it left off.

  • keep_paging (bool) – False if only one page should be fetched.

  • order_id (Optional[str]) – If given, only Transactions for this Amazon Order ID are returned, scoped server-side via Amazon’s transactionTag filter (the days window does not apply).

Return type:

List[Transaction]

Returns:

A list of the requested Transactions.

Session Management

class amazonorders.session.IODefault[source]

Bases: object

Handles input/output from the application. By default, this uses console commands, but this class exists so that it can be overridden when constructing an AmazonSession if input/output should be handled another way.

echo(msg, **kwargs)[source]

Echo a message to the console.

Parameters:
  • msg (str) – The data to send to output.

  • kwargs (Any) – Unused by the default implementation.

Return type:

None

prompt(msg, type=None, **kwargs)[source]

Prompt to the console for user input.

Parameters:
  • msg (str) – The data to use as the input prompt.

  • type (Optional[Any]) – Unused by the default implementation.

  • kwargs (Any) – Unused by the default implementation.

Return type:

Any

Returns:

The user input result.

class amazonorders.session.AmazonSession(username=None, password=None, debug=False, io=<amazonorders.session.IODefault object>, config=None, auth_forms=None, otp_secret_key=None, domain=None)[source]

Bases: object

An interface for interacting with Amazon and authenticating an underlying requests.Session. Utilizing this class means session data is maintained between requests. Session data may also persisted after each request, so it can also be maintained between separate instantiations of the class or application.

To get started, call the login function.

username: str | None

An Amazon username. Environment variable AMAZON_USERNAME will override passed in or config value.

password: str | None

An Amazon password. Environment variable AMAZON_PASSWORD will override passed in or config value.

otp_secret_key: str | None

The secret key Amazon provides when manually adding a 2FA authenticator app. Setting this will allow one-time password challenges to be auto-solved. Environment variable AMAZON_OTP_SECRET_KEY will override passed in or config value.

debug: bool

Setting logger to DEBUG will send output to stderr and write an HTML file for all requests made on the session.

io: IODefault

The I/O handler for echoes and prompts.

config: AmazonOrdersConfig

The config to use.

auth_forms: List[AuthForm]

The list of form implementations to use with authentication. If a value is passed for this when instantiating an AmazonSession, ensure that list is populated with the default form implementations. default_auth_forms returns the default chain so callers can extend it instead of duplicating it.

session: Session

The shared session to be used across all requests.

is_authenticated: bool

If login has been executed and successfully logged in the session.

static default_auth_forms(config)[source]

Build the default ordered list of AuthForm instances used by AmazonSession. Callers wishing to inject a custom form (e.g. a third-party WAF Captcha solver) can call this and insert their own handler before passing the list as auth_forms.

Parameters:

config (AmazonOrdersConfig) – The config to bind to each form.

Return type:

List[AuthForm]

Returns:

The default ordered list of AuthForm instances.

request(method, url, persist_cookies=False, **kwargs)[source]

Execute the request against Amazon with base headers, parsing and storing the response.

Parameters:
  • method (str) – The request method to execute.

  • url (str) – The URL to execute method on.

  • persist_cookies (bool) – If True, cookies from the response will be persisted to a file.

  • kwargs (Any) – Remaining kwargs will be passed to requests.request.

Return type:

AmazonSessionResponse

Returns:

The response from the executed request.

get(url, **kwargs)[source]

Perform a GET request.

Parameters:
Return type:

AmazonSessionResponse

Returns:

The response from the executed request.

post(url, **kwargs)[source]

Perform a POST request.

Parameters:
Return type:

AmazonSessionResponse

Returns:

The response from the executed request.

login()[source]

Execute an Amazon login process. This will include the sign-in page, and may also include OTP (if 2FA is enabled for your account), Captcha challenges, and any other forms in auth_forms.

If successful, is_authenticated will be set to True.

If existing session data is already persisted, calling this function will still attempt to reauthenticate to refresh it.

Return type:

None

logout()[source]

Logout and close the existing Amazon session and clear cookies.

Return type:

None

build_response_error(response)[source]

Build an error message from the given response.

Parameters:

response (Response) – The response to check and build a response.

Return type:

str

Returns:

The error message.

check_response(amazon_session_response, meta=None)[source]

Check the response to ensure it appears to be returning a valid response, and that it is still authenticated. We detect if authentication has expired by checking for redirects to the login page. Raise an error if the response is not going to contain the requested data for parsing.

Parameters:
Return type:

None

class amazonorders.forms.AuthForm(config, selector, error_selector=None, critical=False)[source]

Bases: ABC

The base class of an authentication <form> that can be submitted.

The base implementation will attempt to auto-solve Captcha when the optional amazoncaptcha dependency is installed (pip install amazon-orders[captcha], available on Python <=3.12 only). If auto-solve is unavailable or fails, it will use the default image view to show the Captcha prompt, and it will also pass the image URL to prompt as img_url.

config: AmazonOrdersConfig

The config to use.

selector: str | None

The CSS selector for the <form>.

error_selector: str

The CSS selector for the error div when form submission fails.

critical: bool

If True, form submission failures will raise AmazonOrdersAuthError.

amazon_session: AmazonSession | None

The AmazonSession on which to submit the form.

form: Tag | None

The selected <form>.

data: Dict[str, Any] | None

The <form> data that will be submitted.

select_form(amazon_session, parsed)[source]

Using the selector defined on this instance, select the <form> for the given Tag.

Parameters:
  • amazon_session (AmazonSession) – The AmazonSession on which to submit the form.

  • parsed (Tag) – The Tag from which to select the <form>.

Return type:

bool

Returns:

Whether the <form> selection was successful.

fill_form(additional_attrs=None)[source]

Populate the data field with values from the <form>, including any additional attributes passed.

Parameters:

additional_attrs (Optional[Dict[str, Any]]) – Additional attributes to add to the <form> data for submission.

Return type:

None

submit(last_response)[source]

Submit the populated <form>.

Parameters:

last_response (Response) – The response of the request that fetched the form.

Return type:

AmazonSessionResponse

Returns:

The response from the executed request.

clear_form()[source]

Clear the populated <form> so this class can be reused.

Return type:

None

class amazonorders.forms.SignInForm(config, selector=None, solution_attr_key='email')[source]

Bases: AuthForm

fill_form(additional_attrs=None)[source]

Populate the data field with values from the <form>, including any additional attributes passed.

Parameters:

additional_attrs (Optional[Dict[str, Any]]) – Additional attributes to add to the <form> data for submission.

Return type:

None

class amazonorders.forms.ClaimForm(config, selector=None, solution_attr_key='email')[source]

Bases: AuthForm

fill_form(additional_attrs=None)[source]

Populate the data field with values from the <form>, including any additional attributes passed.

Parameters:

additional_attrs (Optional[Dict[str, Any]]) – Additional attributes to add to the <form> data for submission.

Return type:

None

class amazonorders.forms.IntentForm(config, selector=None, error_selector=None)[source]

Bases: AuthForm

submit(last_response)[source]

When we encounter this form, we can’t submit it, so we display its contents as the error message, since within the context of this library, it is a termination event for the auth flow.

Parameters:

last_response (Response) – The response of the request that fetched the form.

Return type:

AmazonSessionResponse

Returns:

The response from the executed request.

class amazonorders.forms.MfaDeviceSelectForm(config, selector=None, solution_attr_key='otpDeviceContext')[source]

Bases: AuthForm

This will first echo the <form> device choices, then it will pass the list of choices to prompt as choices. The value passed to prompt will be a list of the value from each of input tag.

fill_form(additional_attrs=None)[source]

Populate the data field with values from the <form>, including any additional attributes passed.

Parameters:

additional_attrs (Optional[Dict[str, Any]]) – Additional attributes to add to the <form> data for submission.

Return type:

None

class amazonorders.forms.MfaForm(config, selector=None, solution_attr_key='otpCode')[source]

Bases: AuthForm

fill_form(additional_attrs=None)[source]

Populate the data field with values from the <form>, including any additional attributes passed.

Parameters:

additional_attrs (Optional[Dict[str, Any]]) – Additional attributes to add to the <form> data for submission.

Return type:

None

class amazonorders.forms.CaptchaForm(config, selector=None, error_selector=None, solution_attr_key='cvf_captcha_input')[source]

Bases: AuthForm

fill_form(additional_attrs=None)[source]

Populate the data field with values from the <form>, including any additional attributes passed.

Parameters:

additional_attrs (Optional[Dict[str, Any]]) – Additional attributes to add to the <form> data for submission.

Return type:

None

class amazonorders.forms.AcicAuthBlocker(config)[source]

Bases: AuthForm

select_form(amazon_session, parsed)[source]

Using the selector defined on this instance, select the <form> for the given Tag.

Parameters:
  • amazon_session (AmazonSession) – The AmazonSession on which to submit the form.

  • parsed (Tag) – The Tag from which to select the <form>.

Return type:

bool

Returns:

Whether the <form> selection was successful.

class amazonorders.forms.JSAuthBlocker(config, regex)[source]

Bases: AuthForm

select_form(amazon_session, parsed)[source]

Using the selector defined on this instance, select the <form> for the given Tag.

Parameters:
  • amazon_session (AmazonSession) – The AmazonSession on which to submit the form.

  • parsed (Tag) – The Tag from which to select the <form>.

Return type:

bool

Returns:

Whether the <form> selection was successful.

Configuration

class amazonorders.conf.AmazonOrdersConfig(config_path=None, data=None)[source]

Bases: object

An object containing amazon-orders’s configuration. The state of this object is populated from the config file, if present, when it is instantiated, and it is also persisted back to the config file when save is called.

If overrides are passed in data parameter when this object is instantiated, they will be used to populate the new object, but not persisted to the config file until save is called.

Default values provisioned with the config can be found here.

config_path: str

The path to use for the config file.

set_domain(domain)[source]

Set the active Amazon domain and rebuild constants so URL-derived attributes and region-sensitive headers reflect the change.

Parameters:

domain (str) – The Amazon domain (e.g. amazon.com.au) or full URL.

Return type:

None

update_config(key, value, save=True)[source]

Update the given key/value pair in the config object. By default, this update will also be persisted to the config file. If only the object should be updated without persisting, pass save=False.

Parameters:
  • key (str) – The key to be updated.

  • value (Union[str, int, float]) – The new value.

  • save (bool) – True if the config should be persisted.

Return type:

None

save()[source]

Persist the current state of this config object to the config file.

Return type:

None

amazonorders.constants._BROWSER_PRESETS: Dict[str, Dict[str, str | None]] = {'chromium': {}, 'firefox': {'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 'Accept-Language': 'en-US,en;q=0.5', 'Sec-Ch-Ua': None, 'Sec-Ch-Ua-Mobile': None, 'Sec-Ch-Ua-Platform': None, 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:146.0) Gecko/20100101 Firefox/146.0'}}

Browser-specific header overrides applied on top of the class-level BASE_HEADERS (which already reflects the Chromium fingerprint). A None value removes the key (used to strip headers absent in that engine). Accept-Language here is the browser default; domain-specific TLD overrides still apply on top via _apply_domain.

amazonorders.constants._REGION_LANGUAGES = {'ca': 'en-CA,en;q=0.9,en-US;q=0.8', 'co.uk': 'en-GB,en;q=0.9,en-US;q=0.8', 'com.au': 'en-AU,en;q=0.9,en-US;q=0.8', 'in': 'en-IN,en;q=0.9,en-US;q=0.8', 'sg': 'en-SG,en;q=0.9,en-US;q=0.8'}

Accept-Language values for English-locale Amazon sites, keyed by the TLD suffix that follows amazon.. Looked up dynamically from the user-supplied domain; unknown TLDs keep the base en-US value. This map only governs the Accept-Language header — it is not a list of supported sites and does not affect any other authentication behavior.

amazonorders.constants._REGION_CURRENCIES = {'co.uk': '£', 'in': '₹', 'sg': 'S$'}

CURRENCY_SYMBOL values for English-locale Amazon sites where the storefront actually prefixes prices with a non-$ symbol. amazon.com.au and amazon.ca render prices as plain $ (single-currency context), so they keep the default and are intentionally omitted here. Skipped when AMAZON_CURRENCY_SYMBOL is set.

class amazonorders.constants.Constants(config=None)[source]

Bases: object

A class containing useful constants. Extend and override with constants_class in the config:

from amazonorders.conf import AmazonOrdersConfig

config = AmazonOrdersConfig(data={"constants_class": "my_module.MyConstants"})

URLs and the URL-shaped headers (Origin, Host, Referer) are derived from the active Amazon domain. Accept-Language and CURRENCY_SYMBOL are adjusted for a small set of English-locale TLDs (CURRENCY_SYMBOL only when AMAZON_CURRENCY_SYMBOL is unset). The domain is resolved in this precedence order:

  1. The domain key on AmazonOrdersConfig.

  2. The AMAZON_BASE_URL environment variable.

  3. The default, amazon.com.

Only the English, .com site is officially supported. Other domains may work, but values like openid.assoc_handle are not adjusted automatically — subclass and set constants_class to override them if a non-.com site requires it.

_apply_browser(browser)[source]

Apply browser-specific header overrides for the given browser engine.

Parameters:

browser (str) – Browser engine name — "firefox" or "chromium". Unknown values log a warning and leave BASE_HEADERS unchanged.

Return type:

None

_apply_domain(domain)[source]

Override the URL-derived attributes for the given Amazon domain.

Parameters:

domain (str) – The Amazon domain (e.g. amazon.com.au) or full URL (e.g. https://www.amazon.com.au).

Return type:

None

class amazonorders.selectors.Selector(css_selector, text=None, text_contains=None)[source]

Bases: object

Can be used to extend the definition of a CSS selector, allowing for programmatic inspection of the selections results before determining if selector matches.

css_selector: str

The CSS selector.

text: str | None

The text within the tag that must match exactly (after stripping).

text_contains: str | None

A substring within the tag’s text that must be present (case-insensitive). Evaluated only when text is not set.

class amazonorders.selectors.Selectors[source]

Bases: object

A class containing CSS selectors. Extend and override with selectors_class in the config:

from amazonorders.conf import AmazonOrdersConfig

config = AmazonOrdersConfig(data={"selectors_class": "my_module.MySelectors"})

Entities

class amazonorders.entity.parsable.Parsable(parsed, config)[source]

Bases: object

A base class that contains a parsed representation of the entity, which can be extended to build an entity that utilizes the common the helper methods.

parsed: Tag

Parsed HTML data that can be used to populate the fields of the entity.

config: AmazonOrdersConfig

The config to use.

safe_parse(parse_function, **kwargs)[source]

Execute the given parse function on a field, handling any common parse exceptions and passing them as warnings to the logger (suppressing them as exceptions).

Parameters:
  • parse_function (Callable[..., Any]) – The parse function to attempt safe execution.

  • kwargs (Any) – The kwargs will be passed to parse_function.

Return type:

Any

Returns:

The return value from parse_function.

simple_parse(selector, attr_name=None, text_contains=None, required=False, prefix_split=None, wrap_tag=None, parse_date=False, prefix_split_fuzzy=False, suffix_split=None, suffix_split_fuzzy=False)[source]

Will attempt to extract the text value of the given CSS selector(s) for a field, and is suitable for most basic functionality on a well-formed page.

The selector can be either a str or a list. If a list is given, each selector in the list will be tried.

In most cases the selected tag’s text will be returned, but if wrap_tag is given, the tag itself (wrapped in the class) will be returned.

Parameters:
  • selector (Union[str, list]) – The CSS selector(s) for the field.

  • attr_name (Optional[str]) – If provided, return the value of this attribute on the selected field.

  • text_contains (Optional[str]) – Only select the field if this value is found in its text content.

  • required (bool) – If required, an exception will be thrown instead of returning None.

  • prefix_split (Optional[str]) – Only select the field with the given prefix, returning the right side of the split if so.

  • wrap_tag (Optional[Type]) – Wrap the selected tag in this class before returning.

  • parse_date (bool) – True if the resulting value should be fuzzy parsed in to a date (returning None if parsing fails).

  • prefix_split_fuzzy (bool) – True if the value should still be used even if prefix_split is not found.

  • suffix_split (Optional[str]) – Only select the field with the given suffix, returning the left side of the split if so.

  • suffix_split_fuzzy (bool) – True if the value should still be used even if suffix_split is not found.

Return type:

Any

Returns:

The cleaned up return value from the parsed selector.

safe_simple_parse(selector, **kwargs)[source]

A helper function that uses simple_parse as the parse_function() passed to safe_parse.

Parameters:
  • selector (Union[str, list]) – The CSS selector to pass to simple_parse.

  • kwargs (Any) – The kwargs will be passed to parse_function.

Return type:

Any

Returns:

The return value from simple_parse.

with_base_url(url)[source]

If the given URL is relative, the BASE_URL will be prepended.

Parameters:

url (str) – The URL to check.

Return type:

str

Returns:

The fully qualified URL.

to_currency(value)[source]

Clean up a currency, stripping non-numeric values and returning it as a primitive.

Recognizes the $, £, , and symbols (and leading currency-code letters such as A$ or CDN$), accepts accounting-style negatives in parentheses (e.g. ($1.99)), and treats a literal FREE as 0.0.

Parameters:

value (Union[str, int, float]) – The currency to parse.

Return type:

Union[int, float, None]

Returns:

The currency as a primitive.

class amazonorders.entity.item.Item(parsed, config)[source]

Bases: Parsable

An Item in an Amazon Order. If desired fields are populated as None, ensure full_details is True when retrieving the Order (for instance, with get_order_history), since by default it is False (it will slow down querying).

title: str

The Item title.

The Item link.

price: float | None

The Item price.

seller: Seller | None

The Item Seller.

condition: str | None

The Item condition.

return_eligible_date: date | None

The Item return eligible date.

The Item image URL.

quantity: int | None

The Item quantity.

class amazonorders.entity.order.Order(parsed, config, full_details=False, clone=None, index=None, order_number=None)[source]

Bases: Parsable

An Amazon Order. If desired fields are populated as None, ensure full_details is True when retrieving the Order (for instance, with get_order_history), since by default it is False (enabling slows down querying).

full_details: bool

If the Orders full details were populated from its details page.

index: int | None

Where the Order appeared in the history when it was queried. This will inevitably change (ex. when a new Order is placed, all indexes will then be off by one), but is still captured as it may be applicable in various use-cases. Populated when the Order was fetched through get_order_history (use start_index to correlate), or when the clone has its index set.

cancelled: bool

True if the Order was cancelled. When True, fields like grand_total and the totals on the details page may be None because Amazon stops rendering them.

shipments: List[Shipment]

The Order Shipments.

items: List[Item]

The Order Items.

order_number: str | None

The Order number. May be None only when the Order is cancelled and Amazon stripped the order number from the details page (the order_number parameter is used as a fallback in that case).

The Order details link.

grand_total: float | None

The Order grand total.

order_placed_date: date

The Order placed date.

recipient: Recipient

The Order Recipients.

payment_method: str | None

The Order payment method. Only populated when full_details is True.

payment_method_last_4: int | None

The Order payment method’s last 4 digits. Only populated when full_details is True.

subtotal: float | None

The Order subtotal. Only populated when full_details is True.

shipping_total: float | None

The Order shipping total. Only populated when full_details is True.

free_shipping: float | None

The Order free shipping. Only populated when full_details is True.

promotion_applied: float | None

The Order promotion applied. Only populated when full_details is True.

coupon_savings: float | None

The Order coupon savings. Only populated when full_details is True.

reward_points: float | None

The Order reward points. Only populated when full_details is True.

subscription_discount: float | None

The Order Subscribe & Save discount. Only populated when full_details is True.

total_before_tax: float | None

The Order total before tax. Only populated when full_details is True.

estimated_tax: float | None

The Order estimated tax. Only populated when full_details is True.

refund_total: float | None

The Order refund total. Only populated when full_details is True.

multibuy_discount: float | None

The Multibuy discount. Only populated when full_details is True.

amazon_discount: float | None

The Amazon discount. Only populated when full_details is True.

gift_card: float | None

The Gift Card total. Only populated when full_details is True.

gift_wrap: float | None

The Gift Wrap total. Only populated when full_details is True.

class amazonorders.entity.recipient.Recipient(parsed, config)[source]

Bases: Parsable

The person receiving an Amazon Order.

name: str

The Recipient name.

address: str | None

The Recipient address.

class amazonorders.entity.seller.Seller(parsed, config)[source]

Bases: Parsable

An Amazon Seller of an Amazon Item.

name: str

The Seller name.

The Seller link.

class amazonorders.entity.shipment.Shipment(parsed, config)[source]

Bases: Parsable

An Amazon Shipment, which should contain one or more Item’s.

items: List[Item]

The Shipment Items.

delivery_status: str | None

The Shipment delivery status.

The Shipment tracking link.

class amazonorders.entity.transaction.Transaction(parsed, config, completed_date)[source]

Bases: Parsable

An Amazon Transaction.

completed_date: date

The Transaction completed date.

payment_method: str

The Transaction payment method.

payment_method_last_4: str | None

The Transaction payment method’s last digits, parsed from payment_method. None if no masked digits.

grand_total: float

The Transaction grand total.

is_refund: bool

The Transaction was a refund or not.

order_number: str

The Transaction Order number.

The Transaction Order details link.

seller: str

The Transaction seller name.

Exceptions

exception amazonorders.exception.AmazonOrdersError(error, meta=None)[source]

Bases: Exception

Raised when a general amazon-orders error has occurred.

meta: Dict[str, Any] | None

Metadata for context around the error was raised.

exception amazonorders.exception.AmazonOrdersNotFoundError(error, meta=None)[source]

Bases: AmazonOrdersError

Raised when an Amazon page is not found.

exception amazonorders.exception.AmazonOrdersAuthError(error, meta=None)[source]

Bases: AmazonOrdersError

Raised when an amazon-orders authentication error has occurred.

exception amazonorders.exception.AmazonOrdersAuthRedirectError(error, meta=None)[source]

Bases: AmazonOrdersAuthError

Raised when an amazon-orders session that was previously authenticated redirects to login, indicating the likely need to reauthenticate.

exception amazonorders.exception.AmazonOrdersEntityError(error, meta=None)[source]

Bases: AmazonOrdersError

Raised when an amazon-orders entity parsing error has occurred.

Utility Functions

class amazonorders.util.AmazonSessionResponse(response, bs4_parser)[source]

Bases: object

A wrapper for the requests.Response object, which also contains the parsed HTML.

response: Response

The request’s response object.

parsed: Tag

The parsed HTML from the response.

amazonorders.util.select(parsed, selector)[source]

This is a helper function that extends BeautifulSoup’s select() method to allow for multiple selectors. The selector can be either a str or a list. If a list is given, each selector in the list will be tried until one is found to return a populated list of Tag’s, and that value will be returned.

Parameters:
  • parsed (Tag) – The Tag from which to attempt selection.

  • selector (Union[List[Union[str, Selector]], str, Selector]) – The CSS selector(s) for the field.

Return type:

List[Tag]

Returns:

The selected tag.

amazonorders.util.select_one(parsed, selector)[source]

This is a helper function that extends BeautifulSoup’s select_one() method to allow for multiple selectors. The selector can be either a str or a list. If a list is given, each selector in the list will be tried until one is found to return a populated Tag, and that value will be returned.

Parameters:
  • parsed (Tag) – The Tag from which to attempt selection.

  • selector (Union[List[Union[str, Selector]], str, Selector]) – The CSS selector(s) for the field.

Return type:

Optional[Tag]

Returns:

The selection tag.

amazonorders.util.to_type(value)[source]

Attempt to convert value to its primitive type of int, float, or bool.

If value is an empty string, None will be returned.

Parameters:

value (str) – The value to convert.

Return type:

Union[int, float, bool, str, None]

Returns:

The converted value.

amazonorders.util.load_class(package, clazz)[source]

Import the given class from the given package, and return it.

Parameters:
  • package (List[str]) – The package.

  • clazz (str) – The class to import.

Return type:

Union[Callable, Any]

Returns:

The return class.

amazonorders.util.cleanup_html_text(text)[source]

Cleanup excessive whitespace within text that comes from an HTML block.

Parameters:

text (str) – The text to clean up.

Return type:

str

Returns:

The cleaned up text.