Open stovecbr opened 3 weeks ago
はい、PythonとGoogle Apps Script (GAS)を使用してココナラのデータを収集し、Google Sheetsに書き込む方法をGitHubに公開することができます。以下の手順に従って、必要なスクリプトをGitHubリポジトリに公開します。
PythonスクリプトをGitHubリポジトリに追加します。以下の構成例を使用します。
coconala-scraper/
│
├── README.md
├── requirements.txt
├── scraper.py
└── send_to_sheets.py
README.md
: プロジェクトの説明と使用方法を記述。requirements.txt
: 必要なPythonライブラリを記載。scraper.py
: データ収集および整形を行うPythonスクリプト。send_to_sheets.py
: データをGASウェブアプリに送信するPythonスクリプト。requirements.txt
selenium
pandas
requests
scraper.py
import time
import pandas as pd
from selenium import webdriver
from selenium.webdriver.common.by import By
# WebDriverの設定
driver = webdriver.Chrome(executable_path='/path/to/chromedriver')
# ココナラのページにアクセス
driver.get('https://www.coconala.com/categories')
# データ収集の例
titles = []
for i in range(1, 11): # 上から10個のアイテムを収集
try:
title = driver.find_element(By.XPATH, f'//*[@id="some_xpath_pattern_{i}"]').text
titles.append(title)
except Exception as e:
print(f"Error: {e}")
time.sleep(1)
driver.quit()
# データフレームに整形
df = pd.DataFrame(titles, columns=['Title'])
# データをCSVファイルとして保存
df.to_csv('coconala_titles.csv', index=False)
send_to_sheets.py
import requests
import pandas as pd
# 例として、CSVファイルからデータを読み込む
df = pd.read_csv('coconala_titles.csv')
# DataFrameをJSON形式に変換
json_data = df.to_json(orient='records')
# GASウェブアプリのURL
url = 'https://script.google.com/macros/s/your_deployed_webapp_url/exec'
# POSTリクエストを送信
response = requests.post(url, data=json_data, headers={'Content-Type': 'application/json'})
if response.status_code == 200:
print("Data successfully sent to Google Sheets")
else:
print(f"Failed to send data to Google Sheets: {response.text}")
README.md
# Coconala Scraper
This project scrapes data from Coconala and uploads it to a Google Sheets document using Google Apps Script.
## Requirements
- Python 3.x
- Selenium
- Pandas
- Requests
## Setup
1. Clone the repository:
```sh
git clone https://github.com/yourusername/coconala-scraper.git
cd coconala-scraper
Install the dependencies:
pip install -r requirements.txt
Update scraper.py
with the correct path to your ChromeDriver and the correct XPaths.
Update send_to_sheets.py
with your deployed Google Apps Script URL.
Run the scraper to collect data:
python scraper.py
Send the collected data to Google Sheets:
python send_to_sheets.py
GASスクリプトをGoogle Apps Scriptエディタに追加し、デプロイする手順をREADMEに記載します。
function doPost(e) {
var data = JSON.parse(e.postData.contents);
var sheet = SpreadsheetApp.openById('your_spreadsheet_id').getSheetByName('Sheet1');
sheet.clear(); // 必要に応じてシートをクリア
var headers = Object.keys(data[0]);
sheet.appendRow(headers);
data.forEach(function(row) {
var rowData = headers.map(function(header) {
return row[header];
});
sheet.appendRow(rowData);
});
return ContentService.createTextOutput('Success');
}
## Google Apps Script Setup
1. Open Google Sheets and navigate to Extensions > Apps Script.
2. Paste the following script into the script editor:
```javascript
// (Paste the provided GAS script here)
send_to_sheets.py
script with your deployed web app URL.
git add .
git commit -m "Initial commit"
git push origin main
これで、PythonとGASを使用してココナラのデータを収集し、Google Sheetsに書き込む方法をGitHubに公開できます。顧客はREADMEの指示に従って設定を行い、スクリプトを実行することができます。顧客のアカウント情報を知らなくても、スクリプトの実行が可能です。
はい、Pythonだけでデータを収集し、整形し、Google Sheetsに書き込むことができます。以下の手順では、Pythonを使ってWebスクレイピングを行い、Google Sheets APIを使用して収集したデータをGoogle Sheetsに書き込みます。
まず、必要なライブラリをインストールします。以下のコマンドを実行してください。
pip install selenium pandas google-auth google-auth-oauthlib google-auth-httplib2 google-api-python-client
credentials.json
に変更します。scraper.py
以下のスクリプトは、Seleniumを使用してココナラのデータを収集し、データフレームに整形します。
import time
import pandas as pd
from selenium import webdriver
from selenium.webdriver.common.by import By
# WebDriverの設定
driver = webdriver.Chrome(executable_path='/path/to/chromedriver')
# ココナラのページにアクセス
driver.get('https://www.coconala.com/categories')
# データ収集の例
titles = []
for i in range(1, 11): # 上から10個のアイテムを収集
try:
title = driver.find_element(By.XPATH, f'//*[@id="some_xpath_pattern_{i}"]').text
titles.append(title)
except Exception as e:
print(f"Error: {e}")
time.sleep(1)
driver.quit()
# データフレームに整形
df = pd.DataFrame(titles, columns=['Title'])
# データをCSVファイルとして保存
df.to_csv('coconala_titles.csv', index=False)
send_to_sheets.py
次に、Google Sheets APIを使用して、データをGoogle Sheetsに書き込むスクリプトを作成します。
import pandas as pd
import os.path
from google.oauth2 import service_account
from googleapiclient.discovery import build
# Google Sheets APIの設定
SCOPES = ['https://www.googleapis.com/auth/spreadsheets']
SERVICE_ACCOUNT_FILE = 'credentials.json'
creds = None
creds = service_account.Credentials.from_service_account_file(
SERVICE_ACCOUNT_FILE, scopes=SCOPES)
# 使用するスプレッドシートのIDと範囲を設定
SPREADSHEET_ID = 'your_spreadsheet_id'
RANGE_NAME = 'Sheet1!A1'
# データをCSVファイルから読み込む
df = pd.read_csv('coconala_titles.csv')
# データをリストに変換
values = [df.columns.values.tolist()] + df.values.tolist()
# データをGoogle Sheetsに書き込む
service = build('sheets', 'v4', credentials=creds)
sheet = service.spreadsheets()
request = sheet.values().update(spreadsheetId=SPREADSHEET_ID, range=RANGE_NAME,
valueInputOption='RAW', body={'values': values})
response = request.execute()
print("Data successfully sent to Google Sheets")
python scraper.py
python send_to_sheets.py
scraper.py
) を使用して、ココナラからデータを収集し、CSVファイルに保存します。send_to_sheets.py
)。この方法により、Pythonのみでデータの収集とGoogle Sheetsへの書き込みを行うことができ、外部サービスの設定が不要になります。また、顧客のGoogleアカウント情報を開発者が知る必要もありません。
PythonだけでWebスクレイピングとGoogle Sheetsへのデータ書き込みを行う場合、顧客に提供する方法としては、スクリプトと設定方法をパッケージ化して提供するのが一般的です。以下の手順に従って、顧客が簡単に使えるようにセットアップガイドとスクリプトを準備します。
顧客が簡単にアクセスできるように、スクリプトとドキュメントをGitHubリポジトリに公開します。
以下のファイルを準備します。
README.md
: セットアップと使用方法の説明を記載します。requirements.txt
: 必要なPythonライブラリを記載します。scraper.py
: データ収集スクリプト。send_to_sheets.py
: データをGoogle Sheetsに送信するスクリプト。credentials.json
: Google Sheets APIの認証情報(顧客が取得し、プロジェクトディレクトリに配置)。README.md
# Coconala Data Scraper
This project scrapes data from Coconala and uploads it to a Google Sheets document using Python.
## Requirements
- Python 3.x
- Selenium
- Pandas
- Google API Client
## Setup
1. Clone the repository:
```sh
git clone https://github.com/yourusername/coconala-scraper.git
cd coconala-scraper
Install the dependencies:
pip install -r requirements.txt
Download your credentials.json
file from Google Cloud Console and place it in the project directory.
Update scraper.py
with the correct path to your ChromeDriver and the correct XPaths.
Update send_to_sheets.py
with your Google Sheets ID.
Run the scraper to collect data:
python scraper.py
Send the collected data to Google Sheets:
python send_to_sheets.py
requirements.txt
selenium
pandas
google-auth
google-auth-oauthlib
google-auth-httplib2
google-api-python-client
scraper.py
import time
import pandas as pd
from selenium import webdriver
from selenium.webdriver.common.by import By
# WebDriverの設定
driver = webdriver.Chrome(executable_path='/path/to/chromedriver')
# ココナラのページにアクセス
driver.get('https://www.coconala.com/categories')
# データ収集の例
titles = []
for i in range(1, 11): # 上から10個のアイテムを収集
try:
title = driver.find_element(By.XPATH, f'//*[@id="some_xpath_pattern_{i}"]').text
titles.append(title)
except Exception as e:
print(f"Error: {e}")
time.sleep(1)
driver.quit()
# データフレームに整形
df = pd.DataFrame(titles, columns=['Title'])
# データをCSVファイルとして保存
df.to_csv('coconala_titles.csv', index=False)
send_to_sheets.py
import pandas as pd
from google.oauth2 import service_account
from googleapiclient.discovery import build
# Google Sheets APIの設定
SCOPES = ['https://www.googleapis.com/auth/spreadsheets']
SERVICE_ACCOUNT_FILE = 'credentials.json'
creds = service_account.Credentials.from_service_account_file(
SERVICE_ACCOUNT_FILE, scopes=SCOPES)
# 使用するスプレッドシートのIDと範囲を設定
SPREADSHEET_ID = 'your_spreadsheet_id'
RANGE_NAME = 'Sheet1!A1'
# データをCSVファイルから読み込む
df = pd.read_csv('coconala_titles.csv')
# データをリストに変換
values = [df.columns.values.tolist()] + df.values.tolist()
# データをGoogle Sheetsに書き込む
service = build('sheets', 'v4', credentials=creds)
sheet = service.spreadsheets()
request = sheet.values().update(spreadsheetId=SPREADSHEET_ID, range=RANGE_NAME,
valueInputOption='RAW', body={'values': values})
response = request.execute()
print("Data successfully sent to Google Sheets")
README.md
に従ってセットアップと使用方法を説明します。これにより、顧客は自身のGoogleアカウント情報を開発者に提供せずに、安全かつ効率的にデータの収集とGoogle Sheetsへの書き込みが可能となります。
顧客がコーディングに慣れていない場合でも、Pythonを使用してデータ収集とGoogle Sheetsへの書き込みを簡単に行えるようにするための手順を以下に示します。
顧客がコーディングに慣れていない場合、スクリプトを実行するための明確な手順と必要なツールを提供することが重要です。以下のステップで、顧客が簡単にセットアップと実行を行えるようにします。
Pythonスクリプトを実行ファイル(例えば、Windowsなら.exeファイル)としてパッケージ化することで、顧客はPythonのインストールや環境設定を気にせずに実行できます。PyInstaller
というツールを使って、Pythonスクリプトを実行ファイルに変換できます。
pip install pyinstaller
次に、scraper.py
とsend_to_sheets.py
を実行ファイルに変換します。
pyinstaller --onefile scraper.py
pyinstaller --onefile send_to_sheets.py
これにより、dist/
フォルダにscraper.exe
とsend_to_sheets.exe
が生成されます。これらを顧客に提供します。
以下のような簡単なインストールガイドを提供します。
# Coconala Data Scraper
## はじめに
このガイドでは、ココナラのデータを収集し、Google Sheetsにアップロードする手順を説明します。
## 前提条件
- Windows PC
- Google Sheetsのアカウント
## 手順
1. **ファイルのダウンロード**:
- `scraper.exe`と`sheets_uploader.exe`をダウンロードします。
- `credentials.json`ファイルをダウンロードし、同じフォルダに保存します。
2. **Google Sheetsの設定**:
- [Google Cloud Console](https://console.cloud.google.com/)で新しいプロジェクトを作成します。
- Google Sheets APIを有効にします。
- サービスアカウントを作成し、認証情報をダウンロードして`credentials.json`として保存します。
- Google Sheetsドキュメントを作成し、サービスアカウントのメールアドレスを共有します。
3. **データの収集**:
- `scraper.exe`をダブルクリックして実行します。これにより、データが収集され、`coconala_titles.csv`として保存されます。
4. **Google Sheetsへのアップロード**:
- `send_to_sheets.exe`をダブルクリックして実行します。これにより、データがGoogle Sheetsにアップロードされます。
## サポート
セットアップや実行に関する質問があれば、お気軽にお問い合わせください。
ビデオチュートリアルを作成し、顧客に提供することで、手順がより明確になります。動画では、以下のステップを示します。
顧客が一度に必要なファイルをすべてダウンロードできるように、インストールパッケージ(zipファイルなど)を作成し、提供します。このパッケージには、以下のファイルが含まれます。
scraper.exe
send_to_sheets.exe
README.md
credentials.json
)顧客がコーディングに慣れていない場合でも、以下の方法でスクリプトを簡単に使用できるようにします。
これにより、顧客はPythonやコーディングの知識がなくても、簡単にデータ収集とGoogle Sheetsへの書き込みを行えるようになります。
これまでの回答で触れたOAuthに関する内容は、主にGoogle Sheets APIを使用する際の認証に関するもので、ココナラのデータ収集には直接関係していません。以下にそれぞれの概要を整理します。
credentials.json
をダウンロードしてプロジェクトに追加。以下のスクリプトは、Pythonを使用してGoogle Sheetsにデータを書き込む例です。
import pandas as pd
from google.oauth2 import service_account
from googleapiclient.discovery import build
# Google Sheets APIの設定
SCOPES = ['https://www.googleapis.com/auth/spreadsheets']
SERVICE_ACCOUNT_FILE = 'credentials.json'
creds = service_account.Credentials.from_service_account_file(
SERVICE_ACCOUNT_FILE, scopes=SCOPES)
# 使用するスプレッドシートのIDと範囲を設定
SPREADSHEET_ID = 'your_spreadsheet_id'
RANGE_NAME = 'Sheet1!A1'
# データをCSVファイルから読み込む
df = pd.read_csv('coconala_titles.csv')
# データをリストに変換
values = [df.columns.values.tolist()] + df.values.tolist()
# データをGoogle Sheetsに書き込む
service = build('sheets', 'v4', credentials=creds)
sheet = service.spreadsheets()
request = sheet.values().update(spreadsheetId=SPREADSHEET_ID, range=RANGE_NAME,
valueInputOption='RAW', body={'values': values})
response = request.execute()
print("Data successfully sent to Google Sheets")
以下のスクリプトは、Seleniumを使用してココナラのページからデータを収集する例です。
from selenium import webdriver
from selenium.webdriver.common.by import By
# WebDriverの設定
driver = webdriver.Chrome(executable_path='/path/to/chromedriver')
# ココナラのページにアクセス
driver.get('https://www.coconala.com/categories')
# データ収集の例
titles = []
for i in range(1, 11): # 上から10個のアイテムを収集
try:
title = driver.find_element(By.XPATH, f'//*[@id="some_xpath_pattern_{i}"]').text
titles.append(title)
except Exception as e:
print(f"Error: {e}")
driver.quit()
print(titles)
顧客がコーディングに慣れていない場合、以下の方法で提供します。
PyInstaller
を使用して、Pythonスクリプトを実行ファイルに変換します。credentials.json
など)をパッケージ化して提供します。このアプローチにより、顧客は自身のGoogleアカウント情報を開発者に提供することなく、データ収集とGoogle Sheetsへの書き込みを安全かつ効率的に行うことができます。
Pythonを使ってココナラのデータを収集し、Google Sheetsに書き込むスクリプトを顧客に提供する際のファイル構成を以下に示します。この構成は、顧客がスクリプトを簡単にセットアップして実行できるように設計されています。
coconala_scraper/
├── README.md
├── requirements.txt
├── scraper.py
├── send_to_sheets.py
├── credentials.json (not included in the repository; provided by the customer)
├── dist/
│ ├── scraper.exe (generated by PyInstaller)
│ └── send_to_sheets.exe (generated by PyInstaller)
└── data/
└── coconala_titles.csv (generated by scraper.py)
README.md
インストール手順と使用方法を説明するガイドです。
# Coconala Data Scraper
## 概要
このプロジェクトは、ココナラのデータを収集し、Google Sheetsにアップロードするためのツールです。
## 前提条件
- Windows PC
- Google Sheetsアカウント
- ChromeDriver (バージョンはご使用のGoogle Chromeに合わせてください)
## セットアップ
### 1. ファイルのダウンロード
以下のファイルをダウンロードし、同じフォルダに保存します。
- `scraper.exe`
- `send_to_sheets.exe`
- `credentials.json` (Google Cloud Consoleから取得)
### 2. Google Sheets APIの設定
1. [Google Cloud Console](https://console.cloud.google.com/)で新しいプロジェクトを作成します。
2. Google Sheets APIを有効にします。
3. サービスアカウントを作成し、認証情報をダウンロードして`credentials.json`として保存します。
4. Google Sheetsドキュメントを作成し、サービスアカウントのメールアドレスを共有します。
### 3. データの収集
`scraper.exe`をダブルクリックして実行します。これにより、データが収集され、`data/coconala_titles.csv`として保存されます。
### 4. Google Sheetsへのアップロード
`send_to_sheets.exe`をダブルクリックして実行します。これにより、データがGoogle Sheetsにアップロードされます。
## サポート
セットアップや実行に関する質問があれば、お気軽にお問い合わせください。
requirements.txt
Pythonスクリプトの実行に必要なライブラリを記載します。
selenium
pandas
google-auth
google-auth-oauthlib
google-auth-httplib2
google-api-python-client
scraper.py
ココナラのデータを収集してCSVファイルに保存するスクリプトです。
import time
import pandas as pd
from selenium import webdriver
from selenium.webdriver.common.by import By
# WebDriverの設定
driver = webdriver.Chrome(executable_path='./path/to/chromedriver') # ChromeDriverのパスを設定
# ココナラのページにアクセス
driver.get('https://www.coconala.com/categories')
# データ収集の例
titles = []
for i in range(1, 11): # 上から10個のアイテムを収集
try:
title = driver.find_element(By.XPATH, f'//*[@id="some_xpath_pattern_{i}"]').text
titles.append(title)
except Exception as e:
print(f"Error: {e}")
time.sleep(1)
driver.quit()
# データフレームに整形
df = pd.DataFrame(titles, columns=['Title'])
# データをCSVファイルとして保存
df.to_csv('./data/coconala_titles.csv', index=False)
send_to_sheets.py
CSVファイルのデータをGoogle Sheetsに書き込むスクリプトです。
import pandas as pd
from google.oauth2 import service_account
from googleapiclient.discovery import build
# Google Sheets APIの設定
SCOPES = ['https://www.googleapis.com/auth/spreadsheets']
SERVICE_ACCOUNT_FILE = 'credentials.json'
creds = service_account.Credentials.from_service_account_file(
SERVICE_ACCOUNT_FILE, scopes=SCOPES)
# 使用するスプレッドシートのIDと範囲を設定
SPREADSHEET_ID = 'your_spreadsheet_id'
RANGE_NAME = 'Sheet1!A1'
# データをCSVファイルから読み込む
df = pd.read_csv('./data/coconala_titles.csv')
# データをリストに変換
values = [df.columns.values.tolist()] + df.values.tolist()
# データをGoogle Sheetsに書き込む
service = build('sheets', 'v4', credentials=creds)
sheet = service.spreadsheets()
request = sheet.values().update(spreadsheetId=SPREADSHEET_ID, range=RANGE_NAME,
valueInputOption='RAW', body={'values': values})
response = request.execute()
print("Data successfully sent to Google Sheets")
credentials.json
Google Sheets APIの認証情報ファイル。顧客がGoogle Cloud Consoleから取得し、プロジェクトディレクトリに配置します。
PyInstaller
を使用して、scraper.py
とsend_to_sheets.py
を実行ファイルに変換します。
pyinstaller --onefile scraper.py
pyinstaller --onefile send_to_sheets.py
これにより、dist/
フォルダに実行ファイル(scraper.exe
とsend_to_sheets.exe
)が生成されます。これらを顧客に提供します。
README.md
に記載された手順に従い、顧客がスムーズにセットアップできるようにサポートします。これにより、顧客はPythonの知識がなくても、簡単にデータ収集とGoogle Sheetsへの書き込みを行えるようになります。
Dockerコンテナを使用して、ココナラのデータを収集し、Google Sheetsに書き込む環境をセットアップする方法を説明します。以下に必要な手順を示します。
まず、プロジェクトディレクトリにDockerfile
を作成します。このファイルには、Dockerイメージのビルド手順を記述します。
# ベースイメージとしてPythonを使用
FROM python:3.9-slim
# 作業ディレクトリを設定
WORKDIR /app
# 必要なファイルをコピー
COPY requirements.txt requirements.txt
COPY scraper.py scraper.py
COPY send_to_sheets.py send_to_sheets.py
COPY credentials.json credentials.json
# ChromeDriverとGoogle Chromeのインストール
RUN apt-get update && \
apt-get install -y wget unzip && \
wget -q -O - https://dl.google.com/linux/linux_signing_key.pub | apt-key add - && \
sh -c 'echo "deb [arch=amd64] http://dl.google.com/linux/chrome/deb/ stable main" >> /etc/apt/sources.list.d/google-chrome.list' && \
apt-get update && \
apt-get install -y google-chrome-stable && \
wget -O /tmp/chromedriver.zip https://chromedriver.storage.googleapis.com/$(curl -s https://chromedriver.storage.googleapis.com/LATEST_RELEASE)/chromedriver_linux64.zip && \
unzip /tmp/chromedriver.zip chromedriver -d /usr/local/bin/ && \
rm /tmp/chromedriver.zip && \
apt-get clean && \
rm -rf /var/lib/apt/lists/*
# Pythonパッケージのインストール
RUN pip install --no-cache-dir -r requirements.txt
# デフォルトのコマンドを設定
CMD ["python", "scraper.py"]
requirements.txt
の作成必要なPythonパッケージをリストアップします。
selenium
pandas
google-auth
google-auth-oauthlib
google-auth-httplib2
google-api-python-client
前述のscraper.py
とsend_to_sheets.py
を作成します。
import time
import pandas as pd
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options
# Chromeの設定
chrome_options = Options()
chrome_options.add_argument("--headless")
chrome_options.add_argument("--no-sandbox")
chrome_options.add_argument("--disable-dev-shm-usage")
# WebDriverの設定
service = Service('/usr/local/bin/chromedriver')
driver = webdriver.Chrome(service=service, options=chrome_options)
# ココナラのページにアクセス
driver.get('https://www.coconala.com/categories')
# データ収集の例
titles = []
for i in range(1, 11): # 上から10個のアイテムを収集
try:
title = driver.find_element(By.XPATH, f'//*[@id="some_xpath_pattern_{i}"]').text
titles.append(title)
except Exception as e:
print(f"Error: {e}")
time.sleep(1)
driver.quit()
# データフレームに整形
df = pd.DataFrame(titles, columns=['Title'])
# データをCSVファイルとして保存
df.to_csv('./data/coconala_titles.csv', index=False)
import pandas as pd
from google.oauth2 import service_account
from googleapiclient.discovery import build
# Google Sheets APIの設定
SCOPES = ['https://www.googleapis.com/auth/spreadsheets']
SERVICE_ACCOUNT_FILE = 'credentials.json'
creds = service_account.Credentials.from_service_account_file(
SERVICE_ACCOUNT_FILE, scopes=SCOPES)
# 使用するスプレッドシートのIDと範囲を設定
SPREADSHEET_ID = 'your_spreadsheet_id'
RANGE_NAME = 'Sheet1!A1'
# データをCSVファイルから読み込む
df = pd.read_csv('./data/coconala_titles.csv')
# データをリストに変換
values = [df.columns.values.tolist()] + df.values.tolist()
# データをGoogle Sheetsに書き込む
service = build('sheets', 'v4', credentials=creds)
sheet = service.spreadsheets()
request = sheet.values().update(spreadsheetId=SPREADSHEET_ID, range=RANGE_NAME,
valueInputOption='RAW', body={'values': values})
response = request.execute()
print("Data successfully sent to Google Sheets")
プロジェクトディレクトリで次のコマンドを実行してDockerイメージをビルドします。
docker build -t coconala_scraper .
以下のコマンドを実行して、コンテナを起動し、データを収集します。
docker run --rm -v $(pwd)/data:/app/data coconala_scraper
これにより、収集したデータがdata
ディレクトリに保存されます。
次に、収集したデータをGoogle Sheetsにアップロードするために、以下のコマンドを実行します。
docker run --rm -v $(pwd)/data:/app/data coconala_scraper python send_to_sheets.py
この手順を使用することで、顧客は簡単にココナラのデータを収集し、Google Sheetsにアップロードすることができます。Dockerを使用することで、環境の設定や依存関係の問題を最小限に抑えることができます。
以下のPythonスクリプトを実行すると、Pythonのインストール場所とバージョンを表示します:
python3 -c "import sys; print('Python version:', sys.version); print('Python install location:', sys.executable)"
Python version: 3.10.12 (main, Nov 20 2023, 15:14:05) [GCC 11.4.0] Python install location: /usr/bin/python3
# copilot で生成されたコード。 動く。
# PipfileとPipfile.lockから依存関係をインストールします。
RUN pip install pipenv && \
# Pipfileからpipfile.lockを生成します。pipfile.lockが存在する場合は、pipfile.lockを更新します。
# pipfile.lockが存在しない場合は、pipfileからpipfile.lockを生成します。
pipenv lock && \
# pipfile.lockから依存関係をインストールします。
# --systemオプションを指定することで、依存関係をシステム全体にインストールします。
pipenv sync --system
# 酒家さん修正後のコード
COPY --chown=$UID:$GID ./python/Pipfile ./python/Pipfile.lock ./
RUN pip install -U pip && \
pip install pipenv==2024.0.0 && \
pipenv install --system
以下は、ココナラのデータを収集し、Google Sheetsに書き込むための環境をDockerコンテナでセットアップするためのファイル構成です。この構成には、Dockerfile
、Pythonスクリプト、依存関係のリスト、および必要な認証情報ファイルが含まれます。
coconala_scraper/
├── Dockerfile
├── requirements.txt
├── scraper.py
├── send_to_sheets.py
├── credentials.json
├── docker-compose.yml
└── data/
└── coconala_titles.csv (generated by scraper.py)
Dockerfile: Dockerイメージをビルドするための指示を記述します。
# Python 3.12-slimをベースにしたDockerイメージを使用します。
FROM python:3.12-slim
# Pythonがバッファリングを行わないように環境変数を設定します。
ENV PYTHONUNBUFFERED=1
# 必要なパッケージをインストール
RUN apt-get update && apt-get install -y --no-install-recommends \
wget \
unzip \
&& rm -rf /var/lib/apt/lists/*
# ChromeDriverとGoogle Chromeをインストールします。
RUN wget -q -O - https://dl.google.com/linux/linux_signing_key.pub | apt-key add - && \
sh -c 'echo "deb [arch=amd64] http://dl.google.com/linux/chrome/deb/ stable main" >> /etc/apt/sources.list.d/google-chrome.list' && \
apt-get update && \
apt-get install -y google-chrome-stable && \
wget -O /tmp/chromedriver.zip https://chromedriver.storage.googleapis.com/$(curl -s https://chromedriver.storage.googleapis.com/LATEST_RELEASE)/chromedriver_linux64.zip && \
unzip /tmp/chromedriver.zip chromedriver -d /usr/local/bin/ && \
rm /tmp/chromedriver.zip
# pipをアップグレードし、必要なPythonパッケージをインストールします。
COPY requirements.txt .
RUN pip install --upgrade pip && pip install -r requirements.txt
# 作業ディレクトリを設定します。
WORKDIR /app
# プロジェクトファイルをコピーします。
COPY . .
# デフォルトのコマンドを設定します。
CMD ["python", "scraper.py"]
requirements.txt: 必要なPythonパッケージのリストを記述します。
selenium
pandas
google-auth
google-auth-oauthlib
google-auth-httplib2
google-api-python-client
scraper.py: ココナラのデータを収集するためのPythonスクリプト。
import time
import pandas as pd
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options
# Chromeの設定
chrome_options = Options()
chrome_options.add_argument("--headless")
chrome_options.add_argument("--no-sandbox")
chrome_options.add_argument("--disable-dev-shm-usage")
# WebDriverの設定
service = Service('/usr/local/bin/chromedriver')
driver = webdriver.Chrome(service=service, options=chrome_options)
# ココナラのページにアクセス
driver.get('https://www.coconala.com/categories')
# データ収集の例
titles = []
for i in range(1, 11): # 上から10個のアイテムを収集
try:
title = driver.find_element(By.XPATH, f'//*[@id="some_xpath_pattern_{i}"]').text
titles.append(title)
except Exception as e:
print(f"Error: {e}")
time.sleep(1)
driver.quit()
# データフレームに整形
df = pd.DataFrame(titles, columns=['Title'])
# データをCSVファイルとして保存
df.to_csv('./data/coconala_titles.csv', index=False)
send_to_sheets.py: 収集したデータをGoogle Sheetsに書き込むためのPythonスクリプト。
import pandas as pd
from google.oauth2 import service_account
from googleapiclient.discovery import build
# Google Sheets APIの設定
SCOPES = ['https://www.googleapis.com/auth/spreadsheets']
SERVICE_ACCOUNT_FILE = 'credentials.json'
creds = service_account.Credentials.from_service_account_file(
SERVICE_ACCOUNT_FILE, scopes=SCOPES)
# 使用するスプレッドシートのIDと範囲を設定
SPREADSHEET_ID = 'your_spreadsheet_id'
RANGE_NAME = 'Sheet1!A1'
# データをCSVファイルから読み込む
df = pd.read_csv('./data/coconala_titles.csv')
# データをリストに変換
values = [df.columns.values.tolist()] + df.values.tolist()
# データをGoogle Sheetsに書き込む
service = build('sheets', 'v4', credentials=creds)
sheet = service.spreadsheets()
request = sheet.values().update(spreadsheetId=SPREADSHEET_ID, range=RANGE_NAME,
valueInputOption='RAW', body={'values': values})
response = request.execute()
print("Data successfully sent to Google Sheets")
credentials.json: Google Sheets APIの認証情報ファイル。このファイルはGoogle Cloud Consoleで取得し、プロジェクトディレクトリに配置します。セキュリティ上、このファイルはGitリポジトリに含めないようにします。
docker-compose.yml: Docker Composeファイル。複数のサービスを定義し、簡単に管理できるようにします。
version: '3'
services:
scraper:
build: .
volumes:
- ./data:/app/data
environment:
- GOOGLE_APPLICATION_CREDENTIALS=/app/credentials.json
command: python scraper.py
send_to_sheets:
build: .
volumes:
- ./data:/app/data
environment:
- GOOGLE_APPLICATION_CREDENTIALS=/app/credentials.json
command: python send_to_sheets.py
Dockerイメージのビルド:
docker-compose build
データ収集コンテナの実行:
docker-compose run scraper
データをGoogle Sheetsに送信するコンテナの実行:
docker-compose run send_to_sheets
これらの手順を使用することで、顧客は簡単にココナラのデータを収集し、Google Sheetsにアップロードすることができます。Dockerを使用することで、環境の設定や依存関係の問題を最小限に抑えることができます。
はい、上記の回答は顧客に提供するための前提で構成されています。ただし、顧客がこのセットアップを実行する際に問題が発生しないように、いくつかの追加情報と手順を提供する必要があります。
以下は、顧客に提供するための完全なガイドです。
coconala_scraper/
├── Dockerfile
├── requirements.txt
├── scraper.py
├── send_to_sheets.py
├── credentials.json (provided by the customer)
├── docker-compose.yml
└── data/
└── coconala_titles.csv (generated by scraper.py)
Dockerfile:
FROM python:3.12-slim
ENV PYTHONUNBUFFERED=1
RUN apt-get update && apt-get install -y --no-install-recommends \
wget \
unzip \
&& rm -rf /var/lib/apt/lists/*
RUN wget -q -O - https://dl.google.com/linux/linux_signing_key.pub | apt-key add - && \
sh -c 'echo "deb [arch=amd64] http://dl.google.com/linux/chrome/deb/ stable main" >> /etc/apt/sources.list.d/google-chrome.list' && \
apt-get update && \
apt-get install -y google-chrome-stable && \
wget -O /tmp/chromedriver.zip https://chromedriver.storage.googleapis.com/$(curl -s https://chromedriver.storage.googleapis.com/LATEST_RELEASE)/chromedriver_linux64.zip && \
unzip /tmp/chromedriver.zip chromedriver -d /usr/local/bin/ && \
rm /tmp/chromedriver.zip
COPY requirements.txt .
RUN pip install --upgrade pip && pip install -r requirements.txt
WORKDIR /app
COPY . .
CMD ["python", "scraper.py"]
requirements.txt:
selenium
pandas
google-auth
google-auth-oauthlib
google-auth-httplib2
google-api-python-client
scraper.py:
import time
import pandas as pd
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options
chrome_options = Options()
chrome_options.add_argument("--headless")
chrome_options.add_argument("--no-sandbox")
chrome_options.add_argument("--disable-dev-shm-usage")
service = Service('/usr/local/bin/chromedriver')
driver = webdriver.Chrome(service=service, options=chrome_options)
driver.get('https://www.coconala.com/categories')
titles = []
for i in range(1, 11):
try:
title = driver.find_element(By.XPATH, f'//*[@id="some_xpath_pattern_{i}"]').text
titles.append(title)
except Exception as e:
print(f"Error: {e}")
time.sleep(1)
driver.quit()
df = pd.DataFrame(titles, columns=['Title'])
df.to_csv('./data/coconala_titles.csv', index=False)
send_to_sheets.py:
import pandas as pd
from google.oauth2 import service_account
from googleapiclient.discovery import build
SCOPES = ['https://www.googleapis.com/auth/spreadsheets']
SERVICE_ACCOUNT_FILE = 'credentials.json'
creds = service_account.Credentials.from_service_account_file(
SERVICE_ACCOUNT_FILE, scopes=SCOPES)
SPREADSHEET_ID = 'your_spreadsheet_id'
RANGE_NAME = 'Sheet1!A1'
df = pd.read_csv('./data/coconala_titles.csv')
values = [df.columns.values.tolist()] + df.values.tolist()
service = build('sheets', 'v4', credentials=creds)
sheet = service.spreadsheets()
request = sheet.values().update(spreadsheetId=SPREADSHEET_ID, range=RANGE_NAME,
valueInputOption='RAW', body={'values': values})
response = request.execute()
print("Data successfully sent to Google Sheets")
credentials.json:
credentials.json
を取得する必要があります。このファイルはcoconala_scraper
ディレクトリに配置します。docker-compose.yml:
version: '3'
services:
scraper:
build: .
volumes:
- ./data:/app/data
environment:
- GOOGLE_APPLICATION_CREDENTIALS=/app/credentials.json
command: python scraper.py
send_to_sheets:
build: .
volumes:
- ./data:/app/data
environment:
- GOOGLE_APPLICATION_CREDENTIALS=/app/credentials.json
command: python send_to_sheets.py
DockerとDocker Composeのインストール:
プロジェクトのクローンまたはダウンロード:
git clone <repository_url>
cd coconala_scraper
Google Cloud Platformのセットアップ:
credentials.json
ファイルを取得します。詳細な手順はこちらを参照してください。credentials.json
ファイルをプロジェクトディレクトリに配置します。Dockerイメージのビルド:
docker-compose build
データ収集コンテナの実行:
docker-compose run scraper
データをGoogle Sheetsに送信するコンテナの実行:
docker-compose run send_to_sheets
scraper.py
内のXPathセレクタは、実際のココナラのページ構造に基づいて調整する必要があります。send_to_sheets.py
内のSPREADSHEET_ID
は、実際のGoogle SheetsのIDに置き換えてください。credentials.json
は機密情報を含むため、必ずセキュリティに注意し、Gitリポジトリに含めないようにしてください。このガイドに従うことで、顧客は簡単に環境をセットアップし、ココナラのデータを収集し、Google Sheetsに書き込むことができます。顧客がコーディングに慣れていない場合でも、DockerとDocker Composeを使用することで、必要なすべての依存関係が適切にインストールされ、環境が一貫してセットアップされるため、作業が容易になります。
顧客に提供する場合、特に顧客がコーディングに慣れていない場合には、exeファイルのような実行可能ファイルを提供することで、セットアップや実行の手順を簡略化することができます。ただし、PythonスクリプトとDockerを使用する方法でも十分に簡単に設定できる場合があります。
以下は、exeファイルを使用する場合と、Dockerを使用する場合のそれぞれの方法についての詳細な説明です。
まず、Pythonスクリプトをexeファイルに変換するために、PyInstallerを使用します。
pip install pyinstaller
次に、scraper.py
とsend_to_sheets.py
の各スクリプトをexeファイルに変換します。
pyinstaller --onefile scraper.py
pyinstaller --onefile send_to_sheets.py
これにより、dist/
ディレクトリに各スクリプトの実行可能ファイルが生成されます。これらのファイルを顧客に提供します。
顧客は、Google Cloud Consoleでサービスアカウントを作成し、credentials.json
ファイルを取得する必要があります。このファイルは、exeファイルと同じディレクトリに配置するように指示します。
顧客には、以下の手順を提供します:
scraper.exe
とsend_to_sheets.exe
)を任意のディレクトリに配置します。credentials.json
を同じディレクトリに配置します。scraper.exe
をダブルクリックして実行し、データを収集します。send_to_sheets.exe
をダブルクリックして実行し、データをGoogle Sheetsに書き込みます。顧客には、DockerとDocker Composeをインストールするように指示します。インストール手順は公式ドキュメントに従います。
顧客には、プロジェクトのセットアップ方法を説明します。以下の手順を提供します:
プロジェクトのクローンまたはダウンロード。
git clone <repository_url>
cd coconala_scraper
Google Cloud Consoleでサービスアカウントを作成し、credentials.json
を取得し、プロジェクトディレクトリに配置します。
Dockerイメージのビルド。
docker-compose build
データ収集コンテナの実行。
docker-compose run scraper
データをGoogle Sheetsに送信するコンテナの実行。
docker-compose run send_to_sheets
exeファイルを提供する方法:
Dockerを使用する方法:
顧客の技術的な知識とニーズに応じて、どちらの方法を選択するか決定すると良いでしょう。Dockerを使用する方法は、将来的なメンテナンスや拡張が容易であるため、可能であればこちらを推奨します。
現在の docker-compose.yml
を基に、提供するサービスをセットアップするためのファイルを更新する必要があります。以下は、必要な変更を含む新しい docker-compose.yml
ファイルの例です。
docker-compose.yml
version: '3'
services:
scraper:
build:
context: .
dockerfile: Dockerfile
volumes:
- './data:/app/data'
- './credentials.json:/app/credentials.json:ro'
environment:
- GOOGLE_APPLICATION_CREDENTIALS=/app/credentials.json
command: python scraper.py
tty: true
stdin_open: true
send_to_sheets:
build:
context: .
dockerfile: Dockerfile
volumes:
- './data:/app/data'
- './credentials.json:/app/credentials.json:ro'
environment:
- GOOGLE_APPLICATION_CREDENTIALS=/app/credentials.json
command: python send_to_sheets.py
tty: true
stdin_open: true
scraper
と send_to_sheets
の2つのサービスを定義しています。各サービスは異なるPythonスクリプトを実行します。.
)で、同じ Dockerfile
を使用します。./data
ディレクトリをコンテナ内の /app/data
にマウントし、 credentials.json
ファイルを読み取り専用(:ro
)で /app/credentials.json
にマウントします。GOOGLE_APPLICATION_CREDENTIALS
を設定し、Google Sheets APIの認証情報ファイルのパスを指定します。coconala_scraper/
├── Dockerfile
├── requirements.txt
├── scraper.py
├── send_to_sheets.py
├── credentials.json (provided by the customer)
├── docker-compose.yml
└── data/
└── coconala_titles.csv (generated by scraper.py)
DockerとDocker Composeのインストール
プロジェクトのクローンまたはダウンロード
git clone <repository_url>
cd coconala_scraper
Google Cloud Platformのセットアップ
credentials.json
ファイルを取得します。詳細な手順はこちらを参照してください。credentials.json
ファイルをプロジェクトディレクトリに配置します。Dockerイメージのビルド
docker-compose build
データ収集コンテナの実行
docker-compose run scraper
データをGoogle Sheetsに送信するコンテナの実行
docker-compose run send_to_sheets
この手順に従うことで、顧客は簡単にココナラのデータを収集し、Google Sheetsに書き込むことができます。Dockerを使用することで、環境の依存関係や設定を統一し、手順を簡略化することができます。
Google Sheets APIの設定にはいくつかのステップがあります。以下に詳細な手順を示します。これに従うことで、Google Sheets APIを使用してデータを読み書きするための認証情報を取得できます。
credentials.json
ファイルがダウンロードされます。このファイルをプロジェクトディレクトリに配置します。credentials.json
を使用して、Google Sheets APIにアクセスします。以下に、Pythonコードの例を示します。
import pandas as pd
from google.oauth2 import service_account
from googleapiclient.discovery import build
# 認証情報ファイルのパス
SERVICE_ACCOUNT_FILE = 'credentials.json'
# Google Sheets APIのスコープ
SCOPES = ['https://www.googleapis.com/auth/spreadsheets']
# 認証情報を使用して認証
creds = service_account.Credentials.from_service_account_file(
SERVICE_ACCOUNT_FILE, scopes=SCOPES)
# スプレッドシートIDと範囲の設定
SPREADSHEET_ID = 'your_spreadsheet_id'
RANGE_NAME = 'Sheet1!A1'
# 読み込んだデータの設定
df = pd.read_csv('./data/coconala_titles.csv')
values = [df.columns.values.tolist()] + df.values.tolist()
# Google Sheets APIサービスの作成
service = build('sheets', 'v4', credentials=creds)
sheet = service.spreadsheets()
# データをスプレッドシートに書き込む
request = sheet.values().update(spreadsheetId=SPREADSHEET_ID, range=RANGE_NAME,
valueInputOption='RAW', body={'values': values})
response = request.execute()
print("Data successfully sent to Google Sheets")
DockerとDocker Composeのインストール
プロジェクトのクローンまたはダウンロード
git clone <repository_url>
cd coconala_scraper
Google Cloud Platformのセットアップ
credentials.json
ファイルを取得し、プロジェクトディレクトリに配置します。Dockerイメージのビルド
docker-compose build
データ収集コンテナの実行
docker-compose run scraper
データをGoogle Sheetsに送信するコンテナの実行
docker-compose run send_to_sheets
この手順に従うことで、顧客は簡単にGoogle Sheets APIを設定し、データを収集してGoogle Sheetsに書き込むことができます。
credentials.json
ファイルのような機密情報をGitリポジトリに含めないようにするためには、以下の手順を実行します。
.gitignore
ファイルを使用して、特定のファイルやディレクトリをGitの追跡対象から除外します。プロジェクトのルートディレクトリに .gitignore
ファイルを作成し、credentials.json
を含めます。
# .gitignore
credentials.json
.gitignore
ファイルを設定する前に、credentials.json
が既にGitで追跡されている場合は、Gitのインデックスから削除する必要があります。次のコマンドを実行します:
git rm --cached credentials.json
その後、コミットして変更を反映します。
git commit -m "Remove credentials.json from tracking"
credentials.json
ファイルをリポジトリに含めない場合、顧客が自分でファイルを追加できるように指示を提供する必要があります。
credentials.json
ファイルを取得するように指示します。credentials.json
ファイルをプロジェクトディレクトリに配置するように指示します。Docker Composeファイルを更新して、credentials.json
ファイルをマウントする方法を示します。
docker-compose.yml
version: '3'
services:
scraper:
build:
context: .
dockerfile: Dockerfile
volumes:
- './data:/app/data'
- './credentials.json:/app/credentials.json:ro'
environment:
- GOOGLE_APPLICATION_CREDENTIALS=/app/credentials.json
command: python scraper.py
tty: true
stdin_open: true
send_to_sheets:
build:
context: .
dockerfile: Dockerfile
volumes:
- './data:/app/data'
- './credentials.json:/app/credentials.json:ro'
environment:
- GOOGLE_APPLICATION_CREDENTIALS=/app/credentials.json
command: python send_to_sheets.py
tty: true
stdin_open: true
プロジェクトのREADME.md
ファイルを更新して、credentials.json
ファイルをどのように設定するかを説明します。
# Coconala Scraper Project
## セットアップ手順
### 1. リポジトリのクローン
```sh
git clone <repository_url>
cd coconala_scraper
Google Cloud Consoleでサービスアカウントを作成し、credentials.json
ファイルを取得してください。詳細な手順はこちらを参照してください。取得したcredentials.json
ファイルをプロジェクトディレクトリに配置します。
docker-compose build
docker-compose run scraper
docker-compose run send_to_sheets
この手順に従うことで、機密情報であるcredentials.json
ファイルをGitリポジトリに含めることなく、顧客が自分で適切に設定できるようにします。
Google Sheets APIを使用する際、サービスアカウントを作成する必要があります。サービスアカウントには、特定のリソースやAPIにアクセスするための認証情報が含まれています。以下に、サービスアカウント名とIDの詳細、およびサービスアカウントの作成手順を説明します。
サービスアカウントは、Google Cloud内の仮想ユーザーです。特定のプロジェクトやAPIへのアクセス権を持ち、アプリケーションやコンテナがGoogle Cloudリソースにアクセスするために使用されます。サービスアカウントには、次のような情報が含まれます:
coconala-scraper-service-account
。coconala-scraper-service-account@<project-id>.iam.gserviceaccount.com
)。credentials.json
ファイルがダウンロードされます。このファイルは後で使用するため、安全な場所に保管してください。次に、Pythonコードでcredentials.json
を使用してGoogle Sheets APIにアクセスする例を示します。
send_to_sheets.py
import pandas as pd
from google.oauth2 import service_account
from googleapiclient.discovery import build
# 認証情報ファイルのパス
SERVICE_ACCOUNT_FILE = 'credentials.json'
# Google Sheets APIのスコープ
SCOPES = ['https://www.googleapis.com/auth/spreadsheets']
# 認証情報を使用して認証
creds = service_account.Credentials.from_service_account_file(
SERVICE_ACCOUNT_FILE, scopes=SCOPES)
# スプレッドシートIDと範囲の設定
SPREADSHEET_ID = 'your_spreadsheet_id'
RANGE_NAME = 'Sheet1!A1'
# 読み込んだデータの設定
df = pd.read_csv('./data/coconala_titles.csv')
values = [df.columns.values.tolist()] + df.values.tolist()
# Google Sheets APIサービスの作成
service = build('sheets', 'v4', credentials=creds)
sheet = service.spreadsheets()
# データをスプレッドシートに書き込む
request = sheet.values().update(spreadsheetId=SPREADSHEET_ID, range=RANGE_NAME,
valueInputOption='RAW', body={'values': values})
response = request.execute()
print("Data successfully sent to Google Sheets")
以上の手順に従うことで、Google Sheets APIのサービスアカウントを作成し、Pythonコードで使用するための設定が完了します。この方法を使えば、機密情報をリポジトリに含めずに、安全にGoogle Sheets APIにアクセスすることができます。
Google Sheets APIを使用してスプレッドシートにアクセスするには、スプレッドシートの共有設定とGoogle Cloud PlatformでのAPI設定を適切に行う必要があります。以下に、スプレッドシートの設定手順を詳しく説明します。
作成したスプレッドシートのURLからスプレッドシートIDを取得します。URLは次のような形式になっています:
https://docs.google.com/spreadsheets/d/your_spreadsheet_id/edit#gid=0
ここで、your_spreadsheet_id
の部分がスプレッドシートIDです。
スプレッドシートの右上にある「共有」ボタンをクリックします。
「共有」ダイアログで、「ユーザーやグループと共有」をクリックします。
Google Cloudで作成したサービスアカウントのメールアドレスを入力します。メールアドレスは次のような形式です:
your-service-account@your-project-id.iam.gserviceaccount.com
「エディター」権限を選択し、「送信」ボタンをクリックします。
credentials.json
ファイルがダウンロードされます。このファイルをプロジェクトディレクトリに配置します。以下のコマンドを実行して必要なライブラリをインストールします。
pip install google-auth google-auth-oauthlib google-auth-httplib2 google-api-python-client pandas
以下に、Google Sheets APIを使用してデータをスプレッドシートに書き込むためのPythonコードの例を示します。
import pandas as pd
from google.oauth2 import service_account
from googleapiclient.discovery import build
# 認証情報ファイルのパス
SERVICE_ACCOUNT_FILE = 'credentials.json'
# Google Sheets APIのスコープ
SCOPES = ['https://www.googleapis.com/auth/spreadsheets']
# 認証情報を使用して認証
creds = service_account.Credentials.from_service_account_file(
SERVICE_ACCOUNT_FILE, scopes=SCOPES)
# スプレッドシートIDと範囲の設定
SPREADSHEET_ID = 'your_spreadsheet_id'
RANGE_NAME = 'Sheet1!A1'
# 読み込んだデータの設定
df = pd.read_csv('./data/coconala_titles.csv')
values = [df.columns.values.tolist()] + df.values.tolist()
# Google Sheets APIサービスの作成
service = build('sheets', 'v4', credentials=creds)
sheet = service.spreadsheets()
# データをスプレッドシートに書き込む
request = sheet.values().update(spreadsheetId=SPREADSHEET_ID, range=RANGE_NAME,
valueInputOption='RAW', body={'values': values})
response = request.execute()
print("Data successfully sent to Google Sheets")
以上の手順に従ってGoogle Sheets APIの設定を行うことで、スプレッドシートにデータを書き込むことができます。顧客に対しては、適切な手順を提供し、必要な設定を行うように案内します。
SERVICE_ACCOUNT_FILE = 'my_credentials.json'
volumes:
- './my_credentials.json:/app/my_credentials.json:ro'
environment:
- GOOGLE_APPLICATION_CREDENTIALS=/app/my_credentials.json
https://www.googleapis.com/auth/spreadsheets
はGoogle Sheetsに対する全ての読み書き操作を許可します。https://www.googleapis.com/auth/spreadsheets.readonly
に変更することができます。https://www.googleapis.com/auth/spreadsheets
をそのまま使用することをお勧めします。volumes:
- './new_credentials.json:/app/new_credentials.json:ro'
environment:
- GOOGLE_APPLICATION_CREDENTIALS=/app/new_credentials.json
2024/06/10のメモ
PythonとGoogle Apps Script (GAS)を使用する方法
この方法では、Pythonを使用してWebスクレイピングとデータ整形を行い、GASを使用してデータをGoogle Sheetsに書き込みます。以下の手順に従って進めます。
ステップ1: Pythonスクリプトでデータを収集および整形
まず、Pythonスクリプトを使用してデータを収集し、整形します。例として、Seleniumを使用してココナラのデータを収集する方法を示します。
必要なライブラリのインストール
Pythonスクリプトの作成
以下は、Seleniumを使用してデータを収集し、整形するPythonスクリプトの例です。
ステップ2: GASスクリプトの作成
次に、Google Apps Script (GAS)を使用して、データをGoogle Sheetsに書き込むためのスクリプトを作成します。
GASスクリプトの作成
ステップ3: PythonスクリプトからGASウェブアプリにデータを送信
最後に、Pythonスクリプトを使用して収集したデータをGASウェブアプリに送信します。
必要なライブラリのインストール
Pythonスクリプトの更新
以下のPythonスクリプトを使用して、データをGASウェブアプリに送信します。
まとめ
この方法により、顧客のGoogleアカウント情報を開発者が知らなくても、安全かつ効率的にデータの収集とGoogle Sheetsへの書き込みが可能となります。