Skip to content

Commit

Permalink
fix logic to find total listings count as mentioned in issue 1: #1
Browse files Browse the repository at this point in the history
  • Loading branch information
irahorecka committed May 1, 2024
1 parent 402714b commit b64c96e
Showing 1 changed file with 16 additions and 9 deletions.
25 changes: 16 additions & 9 deletions chrono24/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
~~~~~~~~~~~~
"""

import json
import re
from functools import lru_cache

Expand Down Expand Up @@ -219,15 +220,21 @@ def _get_total_count(html):
Raises:
NoListingsFoundException: Raised if the query is invalid or no listing count is found.
"""
try:
listing_count_text = get_text_html_tag(
html.find("div", {"class": "result-page-top"}).find("strong")
)
match = re.search(RE_PATTERN_COMMA_SEPARATED_NUM, listing_count_text)
# Return total listing count as integer, otherwise 0
return int(match.group().replace(",", ""))
except AttributeError as e:
raise NoListingsFoundException("No listings found.") from e
# Find the script tag that contains `window.metaData`
script = html.find("script", text=re.compile("window.metaData"))
# Use regex to extract the JSON string
pattern = re.compile(r"window.metaData = ({.*?});", re.DOTALL)
script_text = script.text
match = pattern.search(script_text)
if match:
metadata_json_str = match[1]
metadata = json.loads(metadata_json_str)
# Only return total count if listings are found
total_count = int(metadata["data"]["searchResult"]["numResult"])
if total_count > 0:
return total_count

raise NoListingsFoundException("No listings found.")


class StandardListing:
Expand Down

0 comments on commit b64c96e

Please sign in to comment.