You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

已获浏览器访问权限的非本人私有Google Sheets,如何通过API获取内容?

Got it, let's work through this 403 issue since you can't get in touch with the sheet owner. The core problem here is that your API call is using a separate identity (like a service account) that the sheet hasn't been shared with, but your browser session is already authenticated with an account that has access. Here are three solid workarounds that leverage that existing access:

1. Switch to User OAuth with gspread (Cleanest Solution)

Instead of using a service account (which needs explicit permission from the owner), authenticate with your own Google account—since you can already access the sheet in your browser, this will let your script use that same access level.

Here's how to set it up:

  1. Install the required packages:
    pip install gspread oauth2client
    
  2. Head to the Google Cloud Console, create a new project (or use an existing one), go to APIs & Services > Credentials, and create an OAuth client ID (select "Desktop app" as the application type). Download the client_secret.json file and save it in your project folder.
  3. Use this script (fill in your client ID, secret, and sheet URL):
    import gspread
    from oauth2client.client import OAuth2WebServerFlow
    from oauth2client.file import Storage
    from oauth2client.tools import run_flow
    
    SCOPES = ['https://www.googleapis.com/auth/spreadsheets.readonly']
    CLIENT_ID = 'YOUR_CLIENT_ID'
    CLIENT_SECRET = 'YOUR_CLIENT_SECRET'
    SHEET_URL = 'YOUR_SHEET_URL'
    
    flow = OAuth2WebServerFlow(
        client_id=CLIENT_ID,
        client_secret=CLIENT_SECRET,
        scope=SCOPES,
        redirect_uri='urn:ietf:wg:oauth:2.0:oob'
    )
    
    storage = Storage('credentials.json')
    credentials = storage.get()
    
    if not credentials or credentials.invalid:
        credentials = run_flow(flow, storage)
    
    gc = gspread.authorize(credentials)
    sheet = gc.open_by_url(SHEET_URL)
    worksheet = sheet.get_worksheet(0)
    print(worksheet.get_all_values())
    

When you run this, it'll pop open a browser window asking you to log in with your Google account (the one that can access the sheet) and grant permission. Once authorized, the script will use your account's access rights—no need for the owner to do anything.

2. Automate Your Browser with Selenium

If you don't want to mess with OAuth, you can just simulate your browser session directly. Selenium will use your existing Chrome/Firefox profile (where you're already logged into Google) to load the sheet and scrape the data.

Example with Selenium:

  1. Install Selenium and download the ChromeDriver matching your Chrome version:
    pip install selenium
    
  2. Use this script (adjust the user data path to match your OS):
    from selenium import webdriver
    from selenium.webdriver.common.by import By
    import time
    
    SHEET_URL = 'YOUR_SHEET_URL'
    
    # Use your existing Chrome profile to stay logged in
    options = webdriver.ChromeOptions()
    # Windows path example:
    options.add_argument("user-data-dir=C:\\Users\\YourName\\AppData\\Local\\Google\\Chrome\\User Data")
    # macOS example:
    # options.add_argument("user-data-dir=/Users/YourName/Library/Application Support/Google/Chrome")
    # Linux example:
    # options.add_argument("user-data-dir=/home/YourName/.config/google-chrome")
    
    driver = webdriver.Chrome(options=options)
    driver.get(SHEET_URL)
    time.sleep(3)  # Give the sheet time to load
    
    # Extract table data
    rows = driver.find_elements(By.TAG_NAME, 'tr')
    sheet_data = []
    for row in rows:
        cells = row.find_elements(By.TAG_NAME, 'td')
        row_content = [cell.text for cell in cells if cell.text]
        if row_content:
            sheet_data.append(row_content)
    
    print(sheet_data)
    driver.quit()
    

This is basically just automating what you'd do manually—no API required, and it uses your existing access.

3. Direct Download with Session Cookies

If you prefer a lighter approach, you can grab the direct export URL from your browser and use your session cookies to download the sheet as CSV/Excel, then read it with Python.

Steps:

  1. Open the sheet in your browser, go to File > Download > Comma-separated values (.csv). Before the download starts, open your browser's DevTools (F12), go to the Network tab, find the GET request for the CSV, and copy its URL.
  2. Export your browser's cookies for docs.google.com (use an extension like "Export Cookies" to get them in a format you can use).
  3. Use requests to download the file:
    import requests
    import pandas as pd
    
    # Paste your cookies here (from the export)
    cookies = {
        'SID': 'your_sid_cookie_value',
        'NID': 'your_nid_cookie_value',
        # Add other relevant cookies from the export
    }
    
    export_url = 'YOUR_COPIED_CSV_EXPORT_URL'
    response = requests.get(export_url, cookies=cookies)
    
    # Save and read the CSV
    with open('sheet_data.csv', 'wb') as f:
        f.write(response.content)
    
    df = pd.read_csv('sheet_data.csv')
    print(df.head())
    

Heads up: Cookies expire after a while, so you'll need to refresh them every few weeks or so.


内容的提问来源于stack exchange,提问作者SpiralDev

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 07:05:35