背景

最近有个需求,需要整理美国主要城市的商家信息做市场分析。手动去 Google Maps 一个一个查太慢了,于是研究了一下批量获取方案,分享出来供大家参考。

本篇教程拆解了Talordata的Google Maps API:如何使用 Talordata 擷取 Google Maps 結果,大家有需求的可以去网站上查看。

需求分析

要实现的目标:

  • 输入:城市 + 商家类型(如 "牙医"、"中餐厅")
  • 输出:该城市所有符合条件的商家信息
  • 数据字段:店名、地址、电话、评分、评价数、营业时间等

技术选型考虑:

  • 不能自己写爬虫,维护成本太高
  • 要稳定,不能用两天就被封
  • 返回数据要是结构化的,方便后续处理

实现方案

经过对比,最终选择了通过 SERP API 的方式来实现。这种方式的原理是:你发请求,API 服务商在后台帮你完成搜索,然后返回结构化的数据。

核心优势:

  • 稳定可靠,不用担心被封
  • 返回 JSON 格式,直接可用
  • 支持批量查询

完整代码

import requests
import pandas as pd
from datetime import datetime

class LocalBusinessFinder:
    """本地商家信息批量查询工具"""
    
    def __init__(self, api_token: str):
        self.api_token = api_token
        self.endpoint = "https://serpapi.talordata.net/serp/v1/request"
    
    def find_businesses(self, business_type: str, city: str, 
                       state: str = None, limit: int = 20):
        """
        查找本地商家
        
        Args:
            business_type: 商家类型,如 "dentist", "restaurant"
            city: 城市名
            state: 州/省份(可选)
            limit: 返回数量上限
        """
        # 构建搜索关键词
        location = f"{city}, {state}" if state else city
        query = f"{business_type} in {location}"
        
        headers = {
            "Authorization": f"Bearer {self.api_token}",
            "Content-Type": "application/x-www-form-urlencoded"
        }
        
        payload = {
            "engine": "google_maps",
            "q": query,
            "num": limit
        }
        
        response = requests.post(
            self.endpoint, 
            headers=headers, 
            data=payload
        )
        
        if response.status_code != 200:
            print(f"Error: {response.status_code}")
            return []
        
        data = response.json()
        places = data.get("places", [])
        
        # 整理数据
        results = []
        for place in places:
            results.append({
                "商家名称": place.get("name", "N/A"),
                "地址": place.get("address", "N/A"),
                "电话": place.get("phone", "N/A"),
                "评分": place.get("rating", "N/A"),
                "评价数": place.get("reviews", 0),
                "类别": place.get("type", "N/A"),
                "网站": place.get("website", "N/A"),
                "纬度": place.get("latitude", "N/A"),
                "经度": place.get("longitude", "N/A"),
                "搜索关键词": query,
                "查询时间": datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            })
        
        return results
    
    def multi_city_search(self, config: list, output_prefix: str = "business_data"):
        """
        多城市批量查询
        
        Args:
            config: 查询配置列表
                   [{"city": "NYC", "state": "NY", "type": "dentist"}, ...]
            output_prefix: 输出文件前缀
        """
        all_data = []
        
        for item in config:
            city = item["city"]
            state = item.get("state")
            business_type = item["type"]
            
            print(f"正在查询: {business_type} in {city}...")
            
            businesses = self.find_businesses(
                business_type=business_type,
                city=city,
                state=state
            )
            
            all_data.extend(businesses)
            print(f"  找到 {len(businesses)} 条记录")
        
        # 保存结果
        df = pd.DataFrame(all_data)
        output_file = f"{output_prefix}_{datetime.now().strftime('%Y%m%d')}.xlsx"
        df.to_excel(output_file, index=False)
        
        print(f"\n查询完成!共获取 {len(all_data)} 条商家信息")
        print(f"数据已保存至: {output_file}")
        
        return df


def main():
    # 初始化(替换为你的 API Token)
    finder = LocalBusinessFinder(api_token="YOUR_API_TOKEN_HERE")
    
    # 定义查询配置
    search_config = [
        # 纽约牙医
        {"city": "New York", "state": "NY", "type": "dentist"},
        # 旧金山中餐
        {"city": "San Francisco", "state": "CA", "type": "chinese restaurant"},
        # 洛杉矶酒店
        {"city": "Los Angeles", "state": "CA", "type": "hotel"},
        # 西雅图咖啡店
        {"city": "Seattle", "state": "WA", "type": "coffee shop"},
        # 芝加哥健身房
        {"city": "Chicago", "state": "IL", "type": "gym"},
    ]
    
    # 执行批量查询
    df = finder.multi_city_search(
        config=search_config,
        output_prefix="us_business"
    )
    
    # 数据分析
    print("\n=== 数据概览 ===")
    print(f"总记录数: {len(df)}")
    print(f"\n各城市商家数量:")
    print(df['搜索关键词'].value_counts())
    
    print(f"\n评分分布:")
    print(df['评分'].describe())
    
    # 找出评分最高的商家
    print(f"\n评分最高的 5 家:")
    top_rated = df.nlargest(5, '评分')[['商家名称', '地址', '评分', '评价数']]
    print(top_rated)


if __name__ == "__main__":
    main()

使用方法

  1. 安装依赖
    pip install requests pandas openpyxl
    

  2. 配置 API Token:替换代码中的 YOUR_API_TOKEN_HERE

  3. 修改查询配置:根据你的需求修改 search_config 列表

  4. 运行脚本

    python business_finder.py
    

    输出示例

    运行后会生成 Excel 文件,包含以下数据:

商家名称 地址 电话 评分 评价数 类别
Dental Care NYC 123 Main St, New York, NY +1 212-555-0100 4.8 256 Dentist
Golden Dragon Restaurant 456 Oak Ave, San Francisco, CA +1 415-555-0200 4.5 128 Chinese Restaurant

进阶技巧

1. 按评分筛选高口碑商家

# 只保留评分 >= 4.5 的商家
high_rated = df[df['评分'] >= 4.5]

2. 计算竞争激烈程度

# 统计每个城市的商家数量
competition = df.groupby('搜索关键词').size().sort_values(ascending=False)

3. 生成热力图数据

# 提取经纬度用于地图可视化
geo_data = df[['商家名称', '纬度', '经度', '评分']].dropna()
geo_data.to_csv('heatmap_data.csv', index=False)

总结

这套方案帮我解决了批量获取本地商家信息的问题:

  • ✅ 稳定可靠,不会被封
  • ✅ 数据结构化,直接可用
  • ✅ 支持批量查询多个城市
  • ✅ 输出 Excel,方便后续分析

代码已经封装成类,可以直接集成到你的项目中。有问题欢迎评论区交流!

Tips:更多类似教程可见Talordata Serpapi,手把手教你节省成本。

更多推荐