无法抓取Google Maps商家电话号码的技术求助
Google Maps商家电话号码爬取问题解决
问题描述
现有通过绝对XPATH定位电话按钮的代码仅在多数场景有效,部分情况无法获取号码:
element = driver.find_element(By.XPATH,"/html/body/div[3]/div[9]/div[9]/div/div/div[1]/div[2]/div/div[1]/div/div/div[9]/div[6]/button") print(element.get_attribute("aria-label"))
尝试通过目标商家详情页爬取更稳定的内容,但遇到爬取困难(目标为巴西Google Maps上的「Altas Horas Lanchonete e Petiscaria」商家页面)。
可行解决方案
1. 优化元素定位逻辑
绝对XPATH极易因页面布局更新失效,改用相对定位+属性匹配:
- 基于按钮的
aria-label文本匹配(适配多语言):
from selenium.webdriver.common.by import By # 匹配包含电话相关描述的按钮 phone_btn = driver.find_element(By.XPATH, '//button[contains(@aria-label, "电话") or contains(@aria-label, "Phone") or contains(@aria-label, "Telefone")]') if phone_btn: print(phone_btn.get_attribute("aria-label").split(":")[-1].strip())
- 基于元素的
data-item-id属性定位(更稳定):
phone_btn = driver.find_element(By.CSS_SELECTOR, 'button[data-item-id*="phone"]') if phone_btn: print(phone_btn.get_attribute("aria-label"))
2. 直接解析页面内嵌的结构化数据
Google Maps会在页面源码中嵌入商家的JSON格式数据,可直接提取无需定位DOM元素:
import json from selenium import webdriver driver.get("目标商家页面URL") page_source = driver.page_source # 提取页面初始化状态中的JSON数据 start_mark = 'window.APP_INITIALIZATION_STATE = ' end_mark = ';' start_idx = page_source.find(start_mark) + len(start_mark) end_idx = page_source.find(end_mark, start_idx) app_data = json.loads(page_source[start_idx:end_idx]) # 遍历数据提取电话号码(路径需根据页面版本微调) phone_numbers = [] # 示例路径:定位到商家联系方式模块 for item in app_data[3][6][0][12]: if item[0] == 17: # 标识为电话类型的字段 phone_numbers.append(item[1]) print("商家电话号码:", phone_numbers)
反爬注意事项
- 增加随机延迟(如
time.sleep(random.uniform(2,5))),模拟真实用户操作 - 避免频繁请求,可搭配代理IP分散请求来源
- 定期检查页面结构或数据路径,Google会不定期更新页面架构
内容的提问来源于stack exchange,提问作者Felipe
相关产品推荐
相关产品推荐

