File size: 6,581 Bytes
1f8acec | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 | 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 |