0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Custom Search APIを利用して検索結果を取得してCSVに出力する

Posted at
import requests
import csv
from datetime import datetime

API_KEY = 'YOUR_GOOGLE_CUSTOM_SEARCH_API_KEY'
CSE_ID = 'YOUR_CUSTOM_SEARCH_ENGINE_ID'
INPUT_CSV_FILE_PATH = 'queries.csv'  # 入力用のCSVファイルのパス
OUTPUT_CSV_FILE_PATH = 'results.csv'  # 出力用のCSVファイルのパス

# Googleカスタム検索を行い、結果を返す関数
def google_search(query, api_key, cse_id):
    url = f"https://www.googleapis.com/customsearch/v1?q={query}&key={api_key}&cx={cse_id}"
    response = requests.get(url)
    return response.json()

# 入力用のCSVファイルを開き、クエリを読み込む
with open(INPUT_CSV_FILE_PATH, 'r') as csvfile:
    csvreader = csv.reader(csvfile)

    # 出力用のCSVファイルを開き、結果を書き込む
    with open(OUTPUT_CSV_FILE_PATH, 'w', newline='', encoding='utf-8') as outcsv:
        csvwriter = csv.writer(outcsv)
        
        # ヘッダーを書き込む
        csvwriter.writerow(["Query", "Rank", "Title", "URL", "Retrieved Time"])
        
        for row in csvreader:
            query = row[0]
            data = google_search(query, API_KEY, CSE_ID)
            
            rank = 1
            retrieved_time = datetime.now().strftime('%a %b %d %H:%M:%S %Y')
            
            if 'items' in data:
                for item in data['items']:
                    csvwriter.writerow([query, rank, item['title'], item['link'], retrieved_time])
                    rank += 1

print(f"Results saved to {OUTPUT_CSV_FILE_PATH}")
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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?