Download src/backend/scraper/google_maps_scraper.py from MonPrinM/README: direct link, hf CLI and curl.
- Browser
- Download file 6.58 kB
-
https://huggingface.co/spaces/MonPrinM/README/resolve/main/src/backend/scraper/google_maps_scraper.py
- Command line
-
hf download hf://spaces/MonPrinM/README/src/backend/scraper/google_maps_scraper.py
-
curl -L -o google_maps_scraper.py https://huggingface.co/spaces/MonPrinM/README/resolve/main/src/backend/scraper/google_maps_scraper.py
6.58 kB
| import json | |
| import re | |
| from playwright.sync_api import sync_playwright | |
| import os | |
| def save_to_jsonl(data, filename): | |
| """Save data to JSONL format""" | |
| with open(filename, 'a', encoding='utf-8') as f: | |
| json.dump(data, f, ensure_ascii=False) | |
| f.write('\n') | |
| def scrape_google_maps(search_query, output_file, logger): | |
| """Google Maps Scraping""" | |
| scraped_count = 0 | |
| is_headless = os.environ.get("HEADLESS_MODE", "False").lower() == "true" | |
| with sync_playwright() as p: | |
| browser = p.chromium.launch(headless=is_headless) | |
| context = browser.new_context( | |
| locale="en-US", | |
| viewport={"width": 1920, "height": 1080} | |
| ) | |
| page = context.new_page() | |
| logger.log(f"Search: {search_query}") | |
| page.goto("https://www.google.com/maps?hl=en", timeout=60000) | |
| # Accept cookies | |
| try: | |
| consent = page.locator("button", has_text="Accept all").or_( | |
| page.locator("button", has_text="Принять все") | |
| ) | |
| if consent.is_visible(timeout=3000): | |
| consent.first.click() | |
| except: | |
| pass | |
| # Search | |
| try: | |
| page.wait_for_selector("input#searchboxinput", timeout=10000) | |
| page.fill("input#searchboxinput", search_query) | |
| page.keyboard.press("Enter") | |
| except Exception as e: | |
| logger.log(f"Search error: {e}", level="ERROR") | |
| browser.close() | |
| return 0 | |
| feed_selector = 'div[role="feed"]' | |
| try: | |
| page.wait_for_selector(feed_selector, timeout=15000) | |
| except: | |
| logger.log("Result list not found", level="ERROR") | |
| browser.close() | |
| return 0 | |
| last_height = 0 | |
| no_change_count = 0 | |
| scraped_links = set() | |
| logger.log("Scrolling and collecting data...") | |
| while True: | |
| # Scrolling | |
| try: | |
| page.locator(feed_selector).evaluate("el => el.scrollTo(0, el.scrollHeight)") | |
| except: | |
| break | |
| page.wait_for_timeout(2000) | |
| cards = page.locator('div[role="article"]').all() | |
| logger.log(f"Cards on screen: {len(cards)}") | |
| for card in cards: | |
| try: | |
| # Google Maps Link | |
| link_locator = card.locator("a").first | |
| maps_href = link_locator.get_attribute("href") if link_locator.count() > 0 else None | |
| if not maps_href or maps_href in scraped_links: | |
| continue | |
| # Get raw text of the entire card (for later phone and address analysis) | |
| full_text_str = card.inner_text() | |
| # Split into lines for convenience | |
| raw_text_list = full_text_str.split('\n') | |
| # Name | |
| aria_label = card.get_attribute("aria-label") | |
| name = aria_label if aria_label else "No Name" | |
| # Find Website | |
| website = None | |
| website_btn = card.locator('a[data-value="Website"]').or_( | |
| card.locator('a[data-value="Сайт"]') | |
| ) | |
| if website_btn.count() > 0: | |
| website = website_btn.first.get_attribute("href") | |
| else: | |
| links = card.locator("a").all() | |
| for lnk in links: | |
| href = lnk.get_attribute("href") | |
| if href and "google.com/maps" not in href and "google.com/search" not in href: | |
| website = href | |
| break | |
| # Rating and Reviews | |
| rating = None | |
| reviews_count = 0 | |
| star_loc = card.locator('span[role="img"]').first | |
| star_aria = star_loc.get_attribute("aria-label") if star_loc.count() > 0 else "" | |
| if star_aria: | |
| rating_match = re.search(r'(\d+[.,]\d+)', star_aria) | |
| if rating_match: | |
| rating = rating_match.group(1).replace(',', '.') | |
| clean_aria = star_aria.replace('\xa0', ' ') | |
| rev_match = re.search(r'(\d+)\s*(reviews?|отзыв)', clean_aria, re.IGNORECASE) | |
| if rev_match: | |
| reviews_count = int(rev_match.group(1)) | |
| if reviews_count == 0: | |
| paren_match = re.search(r'\(\s*(\d+)\s*\)', full_text_str) | |
| if paren_match: | |
| reviews_count = int(paren_match.group(1)) | |
| item = { | |
| "name": name, | |
| "website": website, | |
| "maps_link": maps_href, | |
| "rating": rating, | |
| "reviews": reviews_count, | |
| "raw_text": raw_text_list # Saving raw text | |
| } | |
| save_to_jsonl(item, output_file) | |
| scraped_links.add(maps_href) | |
| scraped_count += 1 | |
| site_status = "YES" if website else "NO" | |
| logger.log(f"Saved: {name} | Website: {site_status}") | |
| except Exception as e: | |
| continue | |
| # Check end of list | |
| new_height = page.locator(feed_selector).evaluate("el => el.scrollHeight") | |
| end_text = page.locator("text=You've reached the end of the list").or_( | |
| page.locator("text=Больше результатов нет") | |
| ).is_visible() | |
| if new_height == last_height: | |
| no_change_count += 1 | |
| if no_change_count >= 3 or end_text: | |
| logger.log("End of list reached") | |
| break | |
| else: | |
| no_change_count = 0 | |
| last_height = new_height | |
| logger.log(f"Total records: {scraped_count}") | |
| browser.close() | |
| return scraped_count |