From 39fa50b5b0f195e0dcbf721a92c469e72da29fda Mon Sep 17 00:00:00 2001 From: James Addison <55152140+jayaddison@users.noreply.github.com> Date: Wed, 12 Oct 2022 11:24:23 +0100 Subject: [PATCH] Use isodate library to attempt ISO 8601 duration parsing in get_minutes (#610) --- recipe_scrapers/_utils.py | 14 +++++++++++++- setup.py | 1 + tests/library/test_utils.py | 12 ++++++++++++ 3 files changed, 26 insertions(+), 1 deletion(-) diff --git a/recipe_scrapers/_utils.py b/recipe_scrapers/_utils.py index 56c86f867..e35511923 100644 --- a/recipe_scrapers/_utils.py +++ b/recipe_scrapers/_utils.py @@ -1,5 +1,8 @@ # mypy: disallow_untyped_defs=False + import html +import isodate +import math import re from ._exceptions import ElementNotFoundInHtml @@ -30,7 +33,7 @@ SERVE_REGEX_TO = re.compile(r"\d+(\s+to\s+|-)\d+", flags=re.I | re.X) -def get_minutes(element, return_zero_on_not_found=False): +def get_minutes(element, return_zero_on_not_found=False): # noqa: C901: TODO if element is None: # to be removed if return_zero_on_not_found: @@ -47,6 +50,15 @@ def get_minutes(element, return_zero_on_not_found=False): time_text = element else: time_text = element.get_text() + + # attempt iso8601 duration parsing + if time_text.startswith("PT"): + try: + duration = isodate.parse_duration(time_text) + return math.ceil(duration.total_seconds() / 60) + except Exception: + pass + if time_text.startswith("P") and "T" in time_text: time_text = time_text.split("T", 2)[1] if "-" in time_text: diff --git a/setup.py b/setup.py index 768ea9707..bbfa60728 100644 --- a/setup.py +++ b/setup.py @@ -27,6 +27,7 @@ install_requires=[ "beautifulsoup4>=4.10.0", "extruct>=0.8.0", + "isodate>=0.6.1", "requests>=2.19.1", "types-beautifulsoup4>=4.11.6", "types-requests>=2.28.10", diff --git a/tests/library/test_utils.py b/tests/library/test_utils.py index dfdbd5d8e..b0f97d3c9 100644 --- a/tests/library/test_utils.py +++ b/tests/library/test_utils.py @@ -71,3 +71,15 @@ def test_get_minutes_handles_dashes(self): def test_get_minutes_handles_to(self): text = "15 to 20 minutes" self.assertEqual(20, get_minutes(text)) + + iso8601_fixtures = { + "PT1H": 60, + "PT20M": 20, + "PT2H10M": 130, + "PT0H9M30S": 10, + } + + def test_get_minutes_handles_iso8601(self): + for text, expected_minutes in self.iso8601_fixtures.items(): + with self.subTest(text=text): + self.assertEqual(expected_minutes, get_minutes(text))