LoginSignup
0
0

More than 1 year has passed since last update.

Sheets APIを使いスプレッドシートの複数の範囲を取得する

Last updated at Posted at 2021-11-03

Sheets APIを使いスプレッドシートの複数の範囲を取得する

スクレイピング時に必要な設定値をグーグルスプレッドシートから一括で取得したい。
検索しても単一の範囲を取得するものばかりでなかなかでてこなかったのでメモ。

離れた範囲を取得する場合

batchGetを使います

・環境
Windows10
Python3.9
すでにスプレッドシートAPIを使う手続き済んでおり、動作確認済みとする。
トークンファイルも、秘密鍵もpythonファイルと同じ場所にある。
サンプルなので鍵の管理については考慮無し。

例:
スプレッドシートの「設定」シートに名前付き範囲が3か所ある。
名前付き範囲3か所それぞれの値をいっぺんに取得したい。

名前付き範囲 名前付き範囲の場所
endpage 設定!E2
startpage 設定!D2
getrange 設定!A1:B3

こんな感じ↓
image.png

ポイント

①batchGetを使う

②名前範囲をリストにして渡す。

③リターンされた値のvalueRangesが名前付き範囲の値。

全貌は下記参照

python
from __future__ import print_function
import os.path
import pathlib
import sys
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials 



def getspredconnect():

    SPREADSHEET_ID="1×××EsYNg9MO〇〇〇pRDu95P4ABpmy×××〇〇rbh-x3XxvDg0" #スプレッドシートのID
    #スプレッドシートの名前付き範囲をリストにする 「設定」シートに名前付き範囲があるものとする
    RANGES=[]
    RANGES.append("設定!startpage")
    RANGES.append("設定!endpage")
    RANGES.append("設定!getrange")

    jsonfile="client_secret_pps.googleusercontent.com.json"  #認証用のカギ
    SCOPES=['https://www.googleapis.com/auth/drive','https://www.googleapis.com/auth/spreadsheets'] 


    args = sys.argv
    p_tmp =pathlib.Path(os.path.dirname(sys.argv[0]))
    jsonfull = os.path.join(os.path.dirname(sys.argv[0]), jsonfile)
    tokenpath = os.path.join(os.path.dirname(sys.argv[0]), "token.json")
    creds = None
    # The file token.json stores the user's access and refresh tokens, and is
    # created automatically when the authorization flow completes for the first
    # time.
    if os.path.exists(tokenpath):
        creds = Credentials.from_authorized_user_file(tokenpath, SCOPES)

    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                jsonfull, SCOPES)
            creds = flow.run_local_server(port=0)
        # Save the credentials for the next run
        with open(tokenpath, 'w') as token:
            token.write(creds.to_json())

    service = build('sheets', 'v4', credentials=creds)       


    #sheet = service.spreadsheets()
    request = service.spreadsheets().values().batchGet(spreadsheetId=SPREADSHEET_ID, ranges=RANGES)
    response = request.execute()       

    #リターンされた値を取得する
    #リターンされた値の全貌は下参照
    aa = response.get('valueRanges', []) 


    #どのような値がリターンされているか確認
    for jsonObj in aa:
        print(jsonObj["values"])   

    #名前付き範囲の値を個別に取得
    print(aa[0]['values'][0][0])
    print(aa[1]['values'][0][0])
    print(aa[2]['values'][0][1])        



if __name__ == '__main__':

   getspredconnect()

リターンされた値

{
  "spreadsheetId": "1×××EsYNg9MO〇〇〇pRDu95P4ABpmy×××〇〇rbh-x3XxvDg0",
  "valueRanges": [
    {
      "range": "'設定'!D2",
      "majorDimension": "ROWS",
      "values": [
        [
          "1"
        ]
      ]
    },
    {
      "range": "'設定'!E2",
      "majorDimension": "ROWS",
      "values": [
        [
          "10"
        ]
      ]
    },
    {
      "range": "'設定'!A1:B3",
      "majorDimension": "ROWS",
      "values": [
        [
          "食べログ新店舗一覧取得",
          "〇"
        ],
        [
          "ヤフー取得",
          "×"
        ],
        [
          "グーグル検索取得",
          "×"
        ]
      ]
    }
  ]
}

グーグルで検索しても、
単一の範囲を取得するものばかりで。
困って、APIの説明ページをポチポチしていたら偶然みつけました。
最初からAPIの説明ページを見ればよかった。

スクレイピングの設定ファイルをローカルにあるエクセルファイルから
スプレッドシートに順次変更しています。
早くなりました。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0