[Python] Google Places API always returns only 20 results, no nextPageToken for any query

Discussão em 'Python' iniciado por Stack, Julho 11, 2025.

  1. Stack

    Stack Membro Participativo

    I’m using Google Places API (v1 places:searchText) to search businesses.

    For every query (e.g. “Namkeen Companies in Delhi”, “Hotels in India”), I only get 20 results.

    The response never includes nextPageToken.

    I’ve added 2-second delay, correct pagination code, but token is always None.

    Official docs say you can get up to 60 results using pagination. Why is nextPageToken missing for every location and query?

    Am I missing something? Or is this API behavior expected? How can I get more results per query?

    Any advice appreciated.

    import requests
    import pandas as pd
    from datetime import datetime
    import time

    # Direct API key (replace with your actual key)
    API_KEY = "API KEY"

    url = "https://places.googleapis.com/v1/places:searchText"
    headers = {
    "Content-Type": "application/json",
    "X-Goog-Api-Key": API_KEY,
    "X-Goog-FieldMask": "places.displayName,places.formattedAddress,places.id,places.types,places.rating,places.userRatingCount"
    }

    # Try multiple queries to get more results like Google Maps
    search_queries = [
    "Hotels in India"
    ]

    all_results = []

    for query in search_queries:
    print(f"\nSearching for: {query}")
    page_token = None
    page = 1

    while True:
    print(f" Requesting page {page}")
    data = {
    "textQuery": query
    }
    if page_token:
    data["pageToken"] = page_token

    response = requests.post(url, headers=headers, json=data)
    print(f" Response status: {response.status_code}")

    if response.status_code != 200:
    print(f" Error: {response.text}")
    break

    resp_json = response.json()
    results = resp_json.get("places", [])
    print(f" Found {len(results)} results on page {page}")

    # Add results to our collection, avoiding duplicates
    for place in results:
    place_id = place.get("id", "")
    if not any(existing.get("id", "") == place_id for existing in all_results):
    all_results.append(place)

    page_token = resp_json.get("nextPageToken")
    if not page_token:
    break
    page += 1
    time.sleep(2) # Google recommends a short delay before using nextPageToken

    print(f"\nTotal unique results found: {len(all_results)}")

    # Prepare data for Excel
    excel_data = []
    for i, place in enumerate(all_results, 1):
    name = place.get("displayName", {}).get("text", "Unknown")
    address = place.get("formattedAddress", "No address")
    place_id = place.get("id", "")
    types = ", ".join(place.get("types", []))
    rating = place.get("rating", "N/A")
    user_rating_count = place.get("userRatingCount", "N/A")

    excel_data.append({
    "S.No": i,
    "Company Name": name,
    "Address": address,
    "Place ID": place_id,
    "Types": types,
    "Rating": rating,
    "Review Count": user_rating_count
    })

    # Create DataFrame and save to Excel
    df = pd.DataFrame(excel_data)

    # Generate filename with timestamp
    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
    filename = f"namkeen_companies_delhi_{timestamp}.xlsx"

    # Save to Excel with formatting
    with pd.ExcelWriter(filename, engine='openpyxl') as writer:
    df.to_excel(writer, sheet_name='Namkeen Companies', index=False)

    # Get the workbook and worksheet
    workbook = writer.book
    worksheet = writer.sheets['Namkeen Companies']

    # Auto-adjust column widths
    for column in worksheet.columns:
    max_length = 0
    column_letter = column[0].column_letter
    for cell in column:
    try:
    if len(str(cell.value)) > max_length:
    max_length = len(str(cell.value))
    except:
    pass
    adjusted_width = min(max_length + 2, 50) # Max width of 50
    worksheet.column_dimensions[column_letter].width = adjusted_width

    print(f"\nResults saved to: {filename}")
    print(f"Total companies found: {len(all_results)}")

    Continue reading...

Compartilhe esta Página